1 public static void main(String[] args) { 2 Map<String,Object> map = new HashMap<>(); 3 map.put("a", 1); 4 5 System.out.println("------------toString()-------------"); 6 try { 7 System.out.println(map.get("b").toString()); 8 } catch (NullPointerException e) { 9 System.out.println("toString():直接会报空指针异常"); //toString()会报空指针异常 10 } 11 System.out.println(); 12 13 System.out.println("------------String.valueOf-------------"); 14 System.out.println("String.valueOf 输出值为:"+String.valueOf(map.get("b"))); //输出值为null 15 System.out.println("“null”.equals String.valueOf输出值为:"+"null".equals(String.valueOf(map.get("b")))); //输出值为null,其实是字符串"null" 16 System.out.println(); 17 18 System.out.println("------------(String)-------------"); 19 System.out.println("(String) 输出值为:"+(String) map.get("b")); //输出为null 20 System.out.println("“null”.equals (String)对比时输出值为:"+"null".equals((String) map.get("b"))); //输出值为null,其实是个空对象 21 try { 22 System.out.println(((String) map.get("b")).equals("null")); 23 } catch (NullPointerException e) { 24 System.out.println("(String) .equals(“null”):对比时会报空指针异常"); //(String)强转,使用equals函数会报空指针异常 25 } 26 }
总结:空对象使用一下函数时:
toString():直接会报空指针异常
String.valueOf:输出值为null,其实是字符串"null"
(String)://输出值为null,其实是个空对象