Java程序员容易犯的10大低级错误

2025-05-29 0 28

本文根据java开发人员在编码过程中容易忽视或经常出错的地方进行了整理,总结了十个比较常见的低级错误点,方便大家学习。

1、不能用“==”比较两个字符串内容相等。

2、 对list做foreach循环时,循环代码中不能修改list的结构。

3、 日志和实际情况不一致;捕获异常后没有在日志中记录异常栈。

4、 魔鬼数字。

5、 空指针异常。

6、 数组下标越界。

7、 将字符串转换为数字时没有捕获numberformatexception异常。

8、 对文件、io、数据库等资源进行操作后没有及时、正确进行释放。

9、 循环体编码时不考虑性能,循环体中包含不需要的重复逻辑。

10、数据类没有重载tostring()方法。

1不能用“==”比较两个字符串内容相等。

解读

两个字符串在比较内容是否相等的时候,如果使用“==”,当两个字符串不是指向内存中同一地址,那么即使这两个字符串内容一样,但是用“==”比较出来的结果也是false。所以两个字符串在比较内容是否相等的时候一定要使用“equals”方法。

示例

下面就是一个字符串比较的例子:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23
publicclass test {

publicstaticvoid main(string[] args)

{

string a = new string("a");

string a2 = "a";

if(a == a2)

{

system.out.println("a == a2return true.");

}

else

{

system.out.println("a == a2 returnfalse.");

}

if(a.equals(a2))

{

system.out.println("a.equals(a2)return true.");

}

else

{

system.out.println("a.equals(a2)return false.");

}

}

}

最终输出的结果为:

a == a2 return false. a.equals(a2) return true.

2 不能在foreach循环中修改list结构

解读

在jdk1.5版以上的foreach循环写法中,不能在循环代码中对正在循环的list的结构进行修改,即对list做add、remove等操作,如果做了这些操作,必须立即退出循环,否则会抛出异常。

示例

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61
publicclass test {

publicstaticvoid main(string[] args)

{

list<person> list = new arraylist<person>();

person p1 = new person("张三", 23);

person p2 = new person("李四", 26);

person p3 = new person("王五", 34);

person p4 = new person("刘二", 15);

person p5 = new person("朱六", 40);

list.add(p1);

list.add(p2);

list.add(p3);

list.add(p4);

list.add(p5);

for(person p : list)

{

if("王五".equals(p.getname()))

{

list.remove(p); // 不能在此时删除对象。

}

elseif("李四".equals(p.getname()))

{

list.remove(p); // 不能在此时删除对象。

}

}

system.out.println(list.size());

}

}

class person

{

private string name;

privateintage;

public person(string name, int age)

{

this.name = name;

this.age = age;

}

public string getname()

{

returnname;

}

publicvoid setname(string name)

{

this.name = name;

}

publicint getage()

{

returnage;

}

publicvoid setage(int age)

{

this.age = age;

}

}

解决上面代码红色部分的问题,可以通过循环取出对象,然后再循环结束后再进行删除。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29
list<person> list = new arraylist<person>();

person p1 = new person(new string("张三"), 23);

person p2 = new person(new string("李四"), 26);

person p3 = new person(new string("王五"), 34);

person p4 = new person(new string("刘二"), 15);

person p5 = new person(new string("朱六"), 40);

list.add(p1);

list.add(p2);

list.add(p3);

list.add(p4);

list.add(p5);

person wangwu = null;

person lisi = null;

for(person p : list)

{

if("王五".equals(p.getname()))

{

wangwu = p;

}

elseif("李四".equals(p.getname()))

{

lisi = p;

}

}

list.remove(wangwu);

list.remove(lisi);

3 日志规范性

解读

日志是定位问题时最重要的依据,业务流程中缺少必要的日志会给定位问题带来很多麻烦,甚至可能造成问题完全无法定位。

异常产生后,必须在日志中以error或以上级别记录异常栈,否则会导致异常栈丢失,无法确认异常产生的位置。并不需要在每次捕获异常时都记录异常日志,这样可能导致异常被多次重复记录,影响问题的定位。但异常发生后其异常栈必须至少被记录一次。

和注释一样,日志也不是越多越好。无用的冗余日志不但不能帮助定位问题,还会干扰问题的定位。而错误的日志更是会误导问题,必须杜绝。

示例

下面的例子虽然打印了很多日志,但基本上都是无用的日志,难以帮助定位问题。甚至还有错误的日志会干扰问题的定位:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31
public voidsaveproduct1(productservicestruct product)

{

log.debug("enter method: addproduct()");

log.debug("check product status");

if(product.getproduct().getproductstatus() != productfieldenum.productstatus.release)

{

thrownew pmsexception(pmserrorcode.product.add_error);

}

log.debug("check tariff");

booleanresult result =checktariff(product.gettariffs());

if(!result.getresult())

{

thrownewpmsexception(pmserrorcode.product.add_error);

}

log.debug("before add product");

productservice prodsrv = (productservice)servicelocator.findservice(productservice.class);

try

{

prodsrv.addproduct(product);

}

catch(bmeexception e)

{

// 未记录异常栈,无法定位问题根源

}

log.debug("after add product");

log.debug("exit method: updateproduct()"); // 错误的日志

}

而下面的例子日志打印的不多,但都是关键信息,可以很好的帮助定位问题:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33
public voidsaveproduct2(productservicestruct product)

{

if(product.getproduct().getproductstatus() != productfieldenum.productstatus.release)

{

log.error(

"productstatus "

+product.getproduct().getproductstatus()

+ "error, expect " + productfieldenum.productstatus.release);

thrownewpmsexception(pmserrorcode.product.add_error);

}

booleanresult result =checktariff(product.gettariffs());

if(!result.getresult())

{

log.error(

"checkproduct tariff error "

+ result.getresultcode()

+ ":"

+ result.getresultdesc());

thrownewpmsexception(pmserrorcode.product.add_error);

}

productservice prodsrv = (productservice)servicelocator.findservice(productservice.class);

try

{

prodsrv.addproduct(product);

}

catch(bmeexception e)

{

log.error("add product error", e);

thrownewpmsexception(pmserrorcode.product.add_error,e);

}

}

4 魔鬼数字

解读

在代码中使用魔鬼数字(没有具体含义的数字、字符串等)将会导致代码难以理解,应该将数字定义为名称有意义的常量。

将数字定义为常量的最终目的是为了使代码更容易理解,所以并不是只要将数字定义为常量就不是魔鬼数字了。如果常量的名称没有意义,无法帮助理解代码,同样是一种魔鬼数字。

在个别特殊情况下,将数字定义为常量反而会导致代码更难以理解,此时就不应该强求将数字定义为常量。

示例

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37
public void addproduct(productservicestruct product)

{

// 魔鬼数字,无法理解3具体代表产品的什么状态

if(product.getproduct().getproductstatus() != 3)

{

thrownewpmsexception(pmserrorcode.product.add_error);

}

booleanresult result =checktariff(product.gettariffs());

if(!result.getresult())

{

thrownew pmsexception(pmserrorcode.product.add_error);

}

}

/**

*产品未激活状态

*/

privatestaticfinalintunactivated = 0;

/**

*产品已激活状态

*/

privatestaticfinalintactivated = 1;

public voidaddproduct2(productservicestruct product)

{

if(product.getproduct().getproductstatus() != activated)

{

thrownewpmsexception(pmserrorcode.product.add_error);

}

booleanresult result =checktariff(product.gettariffs());

if(!result.getresult())

{

thrownewpmsexception(pmserrorcode.product.add_error);

}

}

5 空指针异常

解读

空指针异常是编码过程中最常见的异常,在使用一个对象的时候,如果对象可能为空,并且使用次对象可能会造成空指针异常,那么需要先判断对象是否为空,再使用这个对象。

在进行常量和变量的相等判断时,建议将常量定义为java对象封装类型(如将int类型的常量定义为integer类型),这样在比较时可以将常量放在左边,调用equals方法进行比较,可以省去不必要的判空。

示例

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31
public classnullpointer

{

staticfinal integer result_code_ok = 0;

staticfinal result result_ok = newresult();

publicvoid printresult(integer resultcode)

{

result result = getresult(resultcode);

// result可能为null,造成空指针异常

if(result.isvalid())

{

print(result);

}

}

publicresult getresult(integer resultcode)

{

// 即使resultcode为null,仍然可以正确执行,减少额外的判空语句

if(result_code_ok.equals(resultcode))

{

returnresult_ok;

}

returnnull;

}

publicvoid print(result result)

{

...

}

}

6 下标越界

解读

访问数组、list等容器内的元素时,必须首先检查下标是否越界,杜绝下标越界异常的发生。

示例

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14
publicclass arrayover

{

publicvoid checkarray(string name)

{

// 获取一个数组对象

string[] cids = contentservice.querybyname(name);

if(null != cids)

{

// 只是考虑到cids有可能为null的情况,但是cids完全有可能是个0长度的数组,因此cids[0]有可能数组下标越界

string cid=cids[0];

cid.tochararray();

}

}

}

7 字符串转数字

解读

调用java方法将字符串转换为数字时,如果字符串的格式非法,会抛出运行时异常numberformatexception。

示例

错误例子:

?

1

2

3

4

5
public integer getinteger1(string number)

{

// 如果number格式非法,会抛出numberformatexception

returninteger.valueof(number);

}

正确的处理方法如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13
public integer getinteger2(string number)

{

try

{

returninteger.valueof(number);

}

catch(numberformatexception e)

{

...

//记录日志异常信息

returnnull;

}

}

注意:在捕获异常后一定要记录日志。

8 资源释放

解读

在使用文件、io流、数据库连接等不会自动释放的资源时,应该在使用完毕后马上将其关闭。关闭资源的代码应该在try…catch…finally的finally内执行,否则可能造成资源无法释放。

示例

错误案例如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14
public voidwriteproduct1(productservicestruct product)

{

try

{

filewriter filewriter = new filewriter("");

filewriter.append(product.tostring());

// 如果append()抛出异常,close()方法就不会执行,造成io流长时间无法释放

filewriter.close();

}

catch(ioexception e)

{

...

}

}

关闭io流的正确方法如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30
public voidwriteproduct2(productservicestruct product)

{

filewriter filewriter = null;

try

{

filewriter = new filewriter("");

filewriter.append(product.tostring());

}

catch(ioexception e)

{

...

//记录日志

}

finally

{

// 不管前面是否发生异常,finally中的代码一定会执行

if(filewriter != null)

{

try

{

filewriter.close();

}

catch(ioexception e)

{

...

//记录日志

}

}

}

}

注意:在捕获异常后一定要记录日志。

9 循环体性能

解读

循环体是软件中最容易造成性能问题的地方,所以在进行循环体编码时务必考虑性能问题。

在循环体内重复使用且不会变化的资源(如变量、文件对象、数据库连接等),应该在循环体开始前构造并初始化,避免在循环体内重复和构造初始化造成cpu资源的浪费。

除非业务场景需要,避免在循环体内构造try…catch块,因为每次进入、退出try…catch块都会消耗一定的cpu资源,将try…catch块放在循环体之外可以节省大量的执行时间。

示例

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19
public voidaddproducts(list<productservicestruct> prodlist)

{

for(productservicestruct product : prodlist)

{

// prodsrv在每次循环时都会重新获取,造成不必要的资源消耗

productservice prodsrv =(productservice) servicelocator.findservice(productservice.class);

// 避免在循环体内try...catch,放在循环体之外可以节省执行时间

try

{

prodsrv.addproduct(product);

}

catch(bmeexception e)

{

...

//记录日志

}

}

}

在循环体中遇到字符串相加,一定要使用stringbuffer这个类。

10 数据类重载tostring()方法

解读

数据类如果没有重载tostring()方法,在记录日志的时候会无法记录数据对象的属性值,给定位问题带来困难。

示例

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37
public classmdspproductext

{

privatestring key;

privatestring value;

publicstring getkey()

{

returnkey;

}

publicvoid setkey(string key)

{

this.key = key;

}

publicstring getvalue()

{

returnvalue;

}

publicvoid setvalue(string value)

{

this.value = value;

}

}

class businessprocess

{

privatedebuglog log = logfactory.getdebuglog(businessprocess.class);

publicvoid dobusiness(mdspproductextprodext)

{

try

{

...

}

catch(pmsexception e)

{

// mdspproductext未重载tostring()方法,日志中无法记录对象内属性的值,只能记录对象地址

log.error("error while process prodext " +prodext);

}

}

}

总结

以上所述是小编给大家介绍的java程序员容易犯的10大低级错误,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!

原文链接:http://developer.51cto.com/art/201809/584387.htm

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java程序员容易犯的10大低级错误 https://www.kuaiidc.com/110968.html

相关文章

发表评论
暂无评论