1 private final List<String> l = ... ; 2 3 public String[] getString() { 4 if(l.size() == 0) 5 return null ; 6 } 7 8 String[] s = getString(); 9 //对于一个返回null而不是零长度数组或者集合的方法,每次都要判断!=null 10 if(s != null && Arrays.asList(s).contains("a")){ 11 //dosomething 12 }
1 private final List<String> l = ... ; 2 3 public static final String[] EMPTY_STRING_ARRAY = new String[0] ; 4 public String[] getString() { 5 return l.toArray(EMPTY_STRING_ARRAY) ; 6 }
1 //返回list的情况 2 public List<String> getString() { 3 if(l.isEmpty()) 4 return Collections.emptyList() ; 5 else 6 return new ArrayList<String>(l) ; 7 }
时间: 2024-11-09 05:17:21