工作中,遇到list集合存储null的问题,不确定list能否存储null值。于是写一些demo测试list,set,table,及map存储null的问题。
1.list之arraylist
1 public static void main(String[] args) { 2 String string= null; 3 List list= new ArrayList<String>(); 4 System.out.println("size:"+ list.size()); 5 list.add(string); 6 System.out.println("size:"+ list.size()+ ",list(i):"+list.get(0)); 7 }
run:
size:0
size:1,list(i):null
总结:arraylist集合是能存储null的。
2.list之linkedlist
1 public static void main(String[] args) { 2 List list= new LinkedList<String>(); 3 System.out.println("list.size():"+list.size()); 4 String string= null; 5 list.add(string); 6 System.out.println("list.size():"+list.size()+", list.get(0):"+list.get(0)); 7 }
run:
list.size():0
list.size():1, list.get(0):null
结论:linkedlist能存储null
3.set之hashset:
1 public static void main(String[] args) { 2 // TODO Auto-generated method stub 3 Set set= new HashSet<String>(); 4 System.out.println("set.size():"+set.size()); 5 String string= null; 6 String string2= null; 7 set.add(string); 8 for (Iterator<String> it= set.iterator() ; it.hasNext();) { 9 string2 = it.next(); 10 } 11 System.out.println("set.size():"+set.size()+", set.iterator.next():"+string2); 12 }
run:
set.size():0
set.size():1, set.iterator.next():null
结论:hashset能存储null
4.set之treeset (1):
1 public static void main(String[] args) { 2 Set set= new TreeSet<String>(); 3 System.out.println("set.size():"+set.size()); 4 String string= null; 5 String string2= null; 6 set.add(string); 7 for (Iterator<String> it= set.iterator() ; it.hasNext();) { 8 string2 = it.next(); 9 } 10 System.out.println("set.size():"+set.size()+", set.iterator.next():"+string2); 11 }
run:
set.size():0
Exception in thread "main" java.lang.NullPointerException
at java.util.TreeMap.compare(TreeMap.java:1188)
at java.util.TreeMap.put(TreeMap.java:531)
at java.util.TreeSet.add(TreeSet.java:255)
at com.westward.Demo3.main(Demo3.java:15)
4.set之treeset (2):
public static void main(String[] args) { Set set= new TreeSet<String>(); System.out.println("set.size():"+set.size()); String string= "1"; String string2= null; set.add(string); for (Iterator<String> it= set.iterator() ; it.hasNext();) { string2 = it.next(); } System.out.println("set.size():"+set.size()+", set.iterator.next():"+string2); }
run:
set.size():0
set.size():1, set.iterator.next():1
结论:treeset不能存储null
还有map,及table,未完待续...
你的能量超乎你想象_________