字符串分割和对象初始化小实战: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 }
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 }
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; }
Test2 t2 = new Test2(); t2.setId(new Test1().getId());这样看不会有空指针异常,因为把nullset给了test2对象。但是jdk会进行优化,将上面代码优化成:
Test2 t2 = new Test2(); t2.setId(new Test1().getId().longValue());这时,就会有空指针异常了。