百度调整导致网站排名下降,全国网站排名,做家教网站的资源是什么,短剧小程序开发费用今天在偶然之间发现了一个bug#xff0c;原因居然是使用了containsAll()方法#xff0c;这个问题很简单#xff0c;看以下代码就能发现很大的问题。
package collection;import java.util.ArrayList;
import java.util.List;/*** author heyunlin* version 1.0*/
public cl…今天在偶然之间发现了一个bug原因居然是使用了containsAll()方法这个问题很简单看以下代码就能发现很大的问题。
package collection;import java.util.ArrayList;
import java.util.List;/*** author heyunlin* version 1.0*/
public class ListExample {public static void main(String[] args) {ListInteger list new ArrayList();list.add(2);list.add(3);list.add(3);ListInteger integerList new ArrayList();integerList.add(3);integerList.add(3);integerList.add(3);System.out.println(list);System.out.println(integerList);System.out.println(list.containsAll(integerList));}} 上面的结果最后一行打印的是true因为containsAll()方法的作用类似于遍历指定的集合c通过contains()比较集合中每个元素如果有元素不包含在当前的list对象中就返回false否则返回true为了便于理解写了以下伪代码 public interface ListE extends CollectionE {public boolean containsAll(Collection? c) {for (Object o : c) {if (!this.contains()) {return false;}}return true;}}
因此文章给出的代码等价于
package collection;import java.util.ArrayList;
import java.util.List;/*** author heyunlin* version 1.0*/
public class ListExample {public static void main(String[] args) {ListInteger list new ArrayList();list.add(2);list.add(3);list.add(3);System.out.println(list);System.out.println(integerList);System.out.println(list.contains(3));}}
总结这篇文章分享了一下项目中遇到的关于containsAll()方法使用时应该考虑到的问题当比较的两个list中元素个数相同时可以用equals()方法替代containsAll()方法使用但是在使用之前需要对两个集合排序因为List的源码里已经说明了只有但集合元素的个数和顺序都一样才返回true。 /*** Compares the specified object with this list for equality. Returns* true if and only if the specified object is also a list, both* lists have the same size, and all corresponding pairs of elements in* the two lists are equal. (Two elements e1 and* e2 are equal if (e1null ? e2null :* e1.equals(e2)).) In other words, two lists are defined to be* equal if they contain the same elements in the same order. This* definition ensures that the equals method works properly across* different implementations of the List interface.** param o the object to be compared for equality with this list* return true if the specified object is equal to this list*/
boolean equals(Object o); 好了文章就分享到这里了感谢阅读~