網(wǎng)站做自簽發(fā)證書(shū)黃金網(wǎng)站軟件免費(fèi)
今天在偶然之間發(fā)現(xiàn)了一個(gè)bug,原因居然是使用了containsAll()方法,這個(gè)問(wèn)題很簡(jiǎn)單,看以下代碼就能發(fā)現(xiàn)很大的問(wèn)題。
package collection;import java.util.ArrayList;
import java.util.List;/*** @author heyunlin* @version 1.0*/
public class ListExample {public static void main(String[] args) {List<Integer> list = new ArrayList<>();list.add(2);list.add(3);list.add(3);List<Integer> 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));}}
上面的結(jié)果最后一行打印的是true,因?yàn)閏ontainsAll()方法的作用類(lèi)似于遍歷指定的集合c,通過(guò)contains()比較集合中每個(gè)元素,如果有元素不包含在當(dāng)前的list對(duì)象中,就返回false,否則返回true,為了便于理解,寫(xiě)了以下偽代碼
public interface List<E> extends Collection<E> {public boolean containsAll(Collection<?> c) {for (Object o : c) {if (!this.contains()) {return false;}}return true;}}
因此,文章給出的代碼等價(jià)于
package collection;import java.util.ArrayList;
import java.util.List;/*** @author heyunlin* @version 1.0*/
public class ListExample {public static void main(String[] args) {List<Integer> 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));}}
總結(jié):這篇文章分享了一下項(xiàng)目中遇到的關(guān)于containsAll()方法使用時(shí)應(yīng)該考慮到的問(wèn)題,當(dāng)比較的兩個(gè)list中元素個(gè)數(shù)相同時(shí),可以用equals()方法替代containsAll()方法使用,但是在使用之前需要對(duì)兩個(gè)集合排序(因?yàn)長(zhǎng)ist的源碼里已經(jīng)說(shuō)明了,只有但集合元素的個(gè)數(shù)和順序都一樣才返回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 (e1==null ? e2==null :* 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);
好了,文章就分享到這里了,感謝閱讀~