add是將傳入的參數(shù)作為當(dāng)前List中的一個(gè)Item存儲(chǔ),即使你傳入一個(gè)List也只會(huì)另當(dāng)前的List增加1個(gè)元素
addAll是傳入一個(gè)List,將此List中的所有元素加入到當(dāng)前List中,也就是當(dāng)前List會(huì)增加的元素個(gè)數(shù)為傳入的List的大小
根本不是同一意義的方法
List、Set中都有方法
addAll(Collection c) :
對于set來說,是將c中所有元素添加到一個(gè)Set中,如果Set中已有某一元素,則不添加,因Set不允許有重復(fù)值
對于List來說,是將c中元素append到一個(gè)List中
//Appends all of the elements in the specified collection to the end of this list
retainAll(Collection c)
兩個(gè)集合求交集,
只保留交集數(shù)據(jù)
//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);
- //結(jié)果:[1, 2, 3, s1, s2, 1] 因List中允許重復(fù)值
- Set s = new HashSet();
- s.add( "1" );
- //s.add(1);
- s.add( "2" );
- s.add( "3" );
- s.addAll(str);
- System.out.println(s);
- //結(jié)果:[3, 2, s2, 1, s1] 因Set中不允許重復(fù)值
- //若為s.add(1) ,數(shù)組ss不變,則結(jié)果為:[3, 2, 1, 1, s2, s1] 因其中兩個(gè)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);
- //結(jié)果:[b]
。。。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

