廢話不多說
直接代碼,注釋解釋一切
Collection c = new ArrayList();
//向集合中添加item
c.add(100);
c.add("name");
c.add("age");
c.add("resunly");
c.add("scan");
//集合大小
System.out.println("CollectionExample c.size(): " + c.size());
System.out.println("CollectionExample c.toString(): " + c.toString());
//檢測集合是否包含某item,如果集合中是對象,将會調用對象自己的equeal方法來比較,下面有例子
System.out.println("CollectionExample c.contains: " + c.contains("name"));
//集合疊代器
Iterator it = c.iterator();
while (it.hasNext()) {
System.out.println(" c.iterator() C.items:" + it.next().toString());
}
List list = new ArrayList();
list.add("name");
list.add("addr");
//檢測集合是否包含另外一個集合,是否是其子集
System.out.println("c.containsAll: " + c.containsAll(list));
//整體添加集合
c.addAll(list);
System.out.println("after add list: " + c.toString());
特别提醒
1.removeAll(list)
//removeAll(list)
//1.如果list是集合的子集,删除集合中包含的list items 并且傳回true;
//2.如果list不是集合的子集,不做動作并且傳回false;
List ss = new ArrayList();
ss.add("test");
ss.add("fox");
System.out.println("removeAll(list):"+c.removeAll(ss));
2.retainAll(list)
//retainAll(list) 和上面的removeAll(list) 删除的資料互補
// 1.如果集合中包含子集list以外的項,删除集合中子集list以外的項,并且傳回true,
// 2.如果集合中沒有子集list以外的項,傳回false.不會做什麼動作。
System.out.println("c.retainAll "+c.retainAll(list));
System.out.println("c.retainAll(list)" + c.toString());
//清空集合
c.clear();
System.out.println("after c.clear(): " + c.size());
3.集合裡面對象 contains的用法示例。
集合中的item 如果為對象,在使用contains()以及containsAll()方法的時候,要實作對象equal方法。
他們調用的是對象自己的equal方法做比較的
Info.java
public class Info{
private String title;
private String link;
private String count;
@Override
public boolean equals(Object o) {
if (this == o) return true; //1.和對象自己比較 直接傳回true
if (!(o instanceof Info)) return false; //2.如果不是該類型的對象 直接傳回false;
Info info = (Info) o; //3.裝箱 Object 成Info對象類型
if (count != null ? !count.equals(info.count) : info.count != null) return false;
return true;
}
@Override
public int hashCode() {
int result = title != null ? title.hashCode() : 0;
result = 31 * result + (link != null ? link.hashCode() : 0);
result = 31 * result + (count != null ? count.hashCode() : 0);
return result;
}
public Info(String title, String link, String count) {
this.title = title;
this.link = link;
this.count = count;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
}
//集合裡面對象items contains的用法示例
Collection cc = new ArrayList();
//添加對象
cc.add(new Info("sum","baidu.com","100"));
cc.add(new Info("com","test.com","5100"));
cc.add(new Info("qiang","sina.com","60"));
List listc = new ArrayList();
listc.add(new Info("sum","baidu.com","100"));
listc.add(new Info("com","test.com","5100"));
listc.add(new Info("qiang","sina.com","60"));
System.out.println("Collection containsAll()方法判斷對象:"+cc.containsAll(listc));
//return true