java 集合之Connection
程序员文章站
2022-05-02 09:57:07
...
废话不多说
直接代码,注释解释一切
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