add是將傳入的參數作為當前List中的一個Item存儲,即使你傳入一個List也只會另當前的List增加1個元素
addAll是傳入一個List,將此List中的所有元素加入到當前List中,也就是當前List會增加的元素個數為傳入的List的大小
根本不是同一意義的方法
List、Set中都有方法
addAll(Collection c) :
對于set來說,是將c中所有元素添加到一個Set中,如果Set中已有某一元素,則不添加,因Set不允許有重復值
對于List來說,是將c中元素append到一個List中
//Appends all of the elements in the specified collection to the end of this list
retainAll(Collection c)
兩個集合求交集,
只保留交集數據
//Retains(保留) only the elements in this list that are contained in the specified collection
- String[] ss = { "s1" , "s2" , "1" };
- List str = Arrays.asList(ss);
- List stList = new ArrayList();
- stList.add( "1" );
- stList.add( "2" );
- stList.add( "3" );
- stList.addAll(str);
- System.out.println(stList);
- //結果:[1, 2, 3, s1, s2, 1] 因List中允許重復值
- Set s = new HashSet();
- s.add( "1" );
- //s.add(1);
- s.add( "2" );
- s.add( "3" );
- s.addAll(str);
- System.out.println(s);
- //結果:[3, 2, s2, 1, s1] 因Set中不允許重復值
- //若為s.add(1) ,數組ss不變,則結果為:[3, 2, 1, 1, s2, s1] 因其中兩個1類型不同
- List lt1 = new ArrayList();
- lt1.add( "a" );
- lt1.add( "b" );
- lt1.add( "c" );
- List lt2 = new ArrayList();
- lt2.add( "b" );
- lt2.add( "d" );
- lt2.add( "f" );
- List lt3 = new ArrayList();
- lt3.addAll(lt1);
- lt3.retainAll(lt2);
- System.out.println(lt3);
- //結果:[b]
。。。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
