下面是一个示例代码,展示了如何实现返回一个空集合的方法。 importjava.util.ArrayList;importjava.util.List;publicclassExample{publicstaticList<String>getEmptyList(){List<String>emptyList=newArrayList<>();returnemptyList;}publicstaticvoidmain(String[]args){List<String>myList=getEmptyList();System.out.pr...
return -1; }else{ return name.compareTo(o.getName()); } //return 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return age == person.age && name.eq...
public static final <T> List<T> emptyList() {return(List<T>) EMPTY_LIST; } AI代码助手复制代码 我们看到EMPTY_LIST 是Collections类的一个静态常量,而emptyList是支持泛型的。若是不需要泛型的地方可以直接使用 EMPTY_LIST ,若是需要泛型的地方就需要使用emptyList。 通过上面的分析我们可以很清楚的知道什么...
}publicListIterator<E>listIterator() {returnemptyListIterator(); }publicintsize() {return0;}publicbooleanisEmpty() {returntrue;}publicbooleancontains(Object obj) {returnfalse;}publicbooleancontainsAll(Collection<?> c) {returnc.isEmpty(); }publicObject[] toArray() {returnnewObject[0]; }public...
public static finalListemptyList() { return (List) EMPTY_LIST; } 我们看到EMPTY_LIST 是Collections类的一个静态常量,而emptyList是支持泛型的。若是不需要泛型的地方可以直接使用 EMPTY_LIST ,若是需要泛型的地方就需要使用emptyList。 通过上面的分析我们可以很清楚的知道什么时候使用emptyList;Collections集合中...
return emptyListIterator(); } publicint size() {return0;} publicboolean isEmpty() {returntrue;} publicboolean contains(Object obj) {returnfalse;} publicboolean containsAll(Collection<?> c) {return c.isEmpty(); } public Object[] toArray() {returnnew Object[0]; } ...
buildList方法中可能会返回一个"空的List",后续还可能往这个List添加元素(或者移除元素),但是没有注意Collections.emptyList方法返回的是一个EMPTY_LIST: public static finalListemptyList() { return (List) EMPTY_LIST; } 它是一个static final修饰的成员变量,是一个EmptyList类的实例: ...
return new ArrayList<>(); 解析: 先看下源码,其实就是返回了一个常量 list。 EmptyList 继承 AbstractList<E> 仔细查看源码你会发现它没有实现 add() 和 remove() 方法。 使用Collections.emptyList();的好处就是能节省内存开销,因为它一直引用同一对象地址而 new ArrayList<>();是生成新的对象(每次当 new...
publicstaticfinal<T> List<T> emptyList() { return(List<T>) EMPTY_LIST; } 从上面我们可以看出,emptyList不过是对EMPTY_LIST做了一个泛型支持。这点上我们就可以很清晰的了解两者不同的使用场景了!若是不需要泛型的情况,可以直接使用Collections,反之则使用emptyList(). ...
("List cannot be null or empty");}intindex=ThreadLocalRandom.current().nextInt(list.size());returnlist.get(index);}publicstaticvoidmain(String[]args){List<String>fruits=List.of("apple","banana","orange","grape","watermelon");StringrandomFruit=getRandomElement(fruits);System.out.println(...