1、字符串分割问题:
有这样一个需求:某个对象属性(id、name、age、sex、other)按照某个分隔符,打印成一行,然后再split拆分出来。例如:1#hello#12#man#sdfdsf
但事实上我们会遇到某些字段为空的情况,例如:age为空、other为空。这时候就会出现一个“诡异”的情况:如果最后一个字段之前的某些字段为空,split后的size就会是5;但如果最后你个字段为空,那么split后的size就会小于5。
public static void main(String[] args) {
String str = "A#B#C#D#E#";
System.out.println(str.split("#").length);//输出5
}
public static void main(String[] args) {
String str = "####E#";
System.out.println(str.split("#").length);//输出5
}
public static void main(String[] args) {
String str = "##C#D#E#";
System.out.println(str.split("#").length);//输出5
}
下面的是小于5:
public static void main(String[] args) {
String str = "A#B#C#D##";
System.out.println(str.split("#").length);//输出4
}
public static void main(String[] args) {
String str = "A#B####";
System.out.println(str.split("#").length);//输出2
}
最后,对于上面size不一致的问题,想了一个统一的解决办法,就只在最后加一个end,这样无论哪个字段确实,只要最后一个end在,那么久一定会返回size=6。例如:
public static void main(String[] args) {
String str = "A#####end";
System.out.println(str.split("#").length);//返回6
}
public static void main(String[] args) {
String str = "##C#D#E#end";
System.out.println(str.split("#").length);//返回6
}
public static void main(String[] args) {
String str = "#####end";
System.out.println(str.split("#").length);//返回6
}
2、对象初始化:
对于一些字段,如果没有初始化,会被附上null。这时如果再把该字段赋值给另外一个字段,有可能会有空指针异常。
public class Test1 {
private Long id;
}
没有初始化,这时会被附上null。当他被赋值时,就有可能空指针异常:
Test2 t2 = new Test2();
t2.setId(new Test1().getId());
这样看不会有空指针异常,因为把nullset给了test2对象。但是jdk会进行优化,将上面代码优化成:
Test2 t2 = new Test2();
t2.setId(new Test1().getId().longValue());
这时,就会有空指针异常了。