【Java集合】Collection接口中的常用方法
创始人
2025-06-01 00:08:46
0

Collection 接口

Collection 接口是 List、Set 和 Queue 接口的父接口,该接口里定义的方法 既可用于操作 Set 集合,也可用于操作 List 和 Queue 集合。

JDK不提供此接口的任何直接实现,而是提供更具体的子接口(如:Set和List)实现。

在 Java5 之前,Java 集合会丢失容器中所有对象的数据类型,把所有对象都 当成 Object 类型处理;从 JDK 5.0 增加了泛型以后,Java 集合可以记住容 器中对象的数据类型。

Collection接口的方法:

1、添加

 add(Object obj)

 addAll(Collection coll)

2、获取有效元素的个数

 int size()

3、清空集合

 void clear()

4、是否是空集合

 boolean isEmpty()

5、是否包含某个元素

 boolean contains(Object obj):是通过元素的equals方法来判断是否是同一个对象

 boolean containsAll(Collection c):也是调用元素的equals方法来比较的。拿两个集合的元素挨个比较。

6、删除

 boolean remove(Object obj) :通过元素的equals方法判断是否是要删除的那个元素。只会删除找到的第一个元素

 boolean removeAll(Collection coll):取当前集合的差集

7、取两个集合的交集

 boolean retainAll(Collection c):把交集的结果存在当前集合中,不 影响c

8、集合是否相等

 boolean equals(Object obj)

9、转成对象数组

 Object[] toArray()

10、获取集合对象的哈希值

 hashCode()

11、遍历

 iterator():返回迭代器对象,用于集合遍历

  =========================================================================

 举例;

public class CollectionTest {@Testpublic void test1(){Collection collection = new ArrayList();//add(Object e):将元素e添加到集合collection中collection.add("AA");collection.add("AA");collection.add("BB");collection.add(123);//自动装箱collection.add(new Date());//size():获取添加的元素的个数System.out.println(collection.size());//addAll(Collection collection1):将collection集合中的元素添加到当前的集合中Collection collection1 = new ArrayList();collection1.add(111);collection1.add("CC");collection.addAll(collection1);System.out.println(collection.size());System.out.println(collection);//clear():清空集合元素collection.clear();//isEmpty():判断当前集合是否为空System.out.println(collection.isEmpty());}
}

运行结果如下所示

我们将collection.clear();注释。运行结果如下

 例2

import org.junit.Test;import java.util.ArrayList;
import java.util.Collection;/***  Collection接口中声明的方法的测试*/
public class CollectionTest {@Testpublic void test1(){Collection collection = new ArrayList();collection.add(123);collection.add(456);collection.add(new String("Tom"));collection.add(false);Person p = new Person("Jerry", 20);collection.add(p);//contains(Object obj):判断当前集合中是否包含objboolean contains = collection.contains(123);System.out.println(contains);//trueSystem.out.println(collection.contains(new String("Tom")));//trueSystem.out.println(collection.contains(p));//true}
}

Person类


import java.util.Objects;public class Person {private String Name;private int age;public Person() {super();}public Person(String name, int age) {Name = name;this.age = age;}public String getName() {return Name;}public void setName(String name) {Name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person{" +"Name='" + Name + '\'' +", age=" + age +'}';}

运行:

运行结果为true,说明调用了equals()进行判断

我们添加collection.add(new Person("Tom",20));再运行System.out.println(collection.contains(new Person("Tom", 20)));结果就变成了false

我们需要重写Person类的equals()

import java.util.Objects;public class Person {private String Name;private int age;public Person() {super();}public Person(String name, int age) {Name = name;this.age = age;}public String getName() {return Name;}public void setName(String name) {Name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person{" +"Name='" + Name + '\'' +", age=" + age +'}';}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Person person = (Person) o;return age == person.age && Name.equals(person.Name);}@Overridepublic int hashCode() {return Objects.hash(Name, age);}
}

 运行:

我们在来看几个方法

代码如下:

package com.dai.java;import org.junit.Test;import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;public class CollectionTest {@Testpublic void test1(){Collection collection = new ArrayList();collection.add(123);collection.add(456);collection.add(new String("Tom"));collection.add(false);Person p = new Person("Jerry", 20);collection.add(p);collection.add(new Person("Tom",20));//1.contains(Object obj):判断当前集合中是否包含obj//我们再判断时辉调用obj对象的equals()boolean contains = collection.contains(123);System.out.println(contains);//trueSystem.out.println(collection.contains(new String("Tom")));//trueSystem.out.println(collection.contains(p));//trueSystem.out.println(collection.contains(new Person("Tom", 20)));//false//变成true,重写equals()//2.containsAll(Collection collection):判断形参collection中所有元素是否都存在与当前集合中Collection collection1 = Arrays.asList(123,456);collection.containsAll(collection1);}
}

运行结果:

再来看一下删除

boolean remove(Object obj) :通过元素的equals方法判断是否是要删除的那个元素。只会删除找到的第一个元素

    @Testpublic void test2(){//3.remove(Object obj):从当前集合中移除obj元素Collection collection = new ArrayList();collection.add(123);collection.add(456);collection.add(new Person("Jerry", 20));collection.add(new String("Tom"));collection.add(false);collection.remove(123);System.out.println(collection);collection.remove(new Person("Jerry",20));System.out.println(collection);}

运行结果如下:

boolean removeAll(Collection coll):取当前集合的差集

 

    @Testpublic void test2(){//3.remove(Object obj):从当前集合中移除obj元素Collection collection = new ArrayList();collection.add(123);collection.add(456);collection.add(new Person("Jerry", 20));collection.add(new String("Tom"));collection.add(false);//        collection.remove(123);
//        System.out.println(collection);collection.remove(new Person("Jerry",20));System.out.println(collection);//removeAll(Collection coll1):从当前集合中移除coll1中所有的元素Collection coll1 = Arrays.asList(123,4567);collection.removeAll(coll1);System.out.println(collection);}
}

运行结果如下:

retainAll(Collection coll1):交集:获取当前集合coll1集合的交集,并返回给当前集合

    @Testpublic void test3(){Collection collection = new ArrayList();collection.add(123);collection.add(456);collection.add(new Person("Jerry", 20));collection.add(new String("Tom"));collection.add(false);//5.retainAll(Collection coll1):交集:获取当前集合coll1集合的交集,并返回给当前集合Collection coll1 = Arrays.asList(123,456,789);collection.retainAll(coll1);System.out.println(collection);}

 运行结果:

集合是否相等 :boolean equals(Object obj):要想返回true,需要当前集合和形参集合的元素都相同

    @Testpublic void test3(){Collection collection = new ArrayList();collection.add(123);collection.add(456);collection.add(new Person("Jerry", 20));collection.add(new String("Tom"));collection.add(false);//5.retainAll(Collection coll1):交集:获取当前集合coll1集合的交集,并返回给当前集合
//        Collection coll1 = Arrays.asList(123,456,789);
//        collection.retainAll(coll1);
//        System.out.println(collection);//6.equals(Object obj):Collection coll1 = new ArrayList();coll1.add(123);coll1.add(456);coll1.add(new Person("Jerry", 20));coll1.add(new String("Tom"));coll1.add(false);System.out.println(collection.equals(coll1));}

 运行结果:

 如果我们将123和456调换一下位置:

 获取集合对象的哈希值 hashCode()

    @Testpublic void test4(){Collection coll = new ArrayList();coll.add(456);coll.add(123);coll.add(new Person("Jerry", 20));coll.add(new String("Tom"));coll.add(false);//7.hashCode():返回当前对象的哈希值System.out.println(coll.hashCode());}

 运行结果:

转成对象数组Object[] toArray()

 

    @Testpublic void test4(){Collection coll = new ArrayList();coll.add(456);coll.add(123);coll.add(new Person("Jerry", 20));coll.add(new String("Tom"));coll.add(false);//7.hashCode():返回当前对象的哈希值System.out.println(coll.hashCode());//8.集合 ---> 数组:toArray()Object[] arr = coll.toArray();for (int i = 0; i < arr.length; i++) {System.out.println(arr[i]);}}

 运行结果如下:

拓展:数组 ---> 集合:调用Arrays类的静态方法asList()

 

    @Testpublic void test4(){Collection coll = new ArrayList();coll.add(456);coll.add(123);coll.add(new Person("Jerry", 20));coll.add(new String("Tom"));coll.add(false);//7.hashCode():返回当前对象的哈希值System.out.println(coll.hashCode());//8.集合 ---> 数组:toArray()Object[] arr = coll.toArray();for (int i = 0; i < arr.length; i++) {System.out.println(arr[i]);}//拓展:数组  ---> 集合:调用Arrays类的静态方法asList()List list = Arrays.asList(new String[]{"AA", "BB", "CC"});System.out.println(list);}

 运行结果:

 =========================================================================

  结论: 向Collection接口的实现类的对象中添加数据obj时,要求obj所在类重写equals()

感谢观看!!! 

相关内容

热门资讯

嘉兴男子与妻争吵,突然将行李箱... 近日,浙江嘉兴一对夫妻因琐事发生争吵,丈夫突然将装满衣物的行李箱从6楼扔到楼下,引发关注。11月22...
三地107家律所齐聚丰台,京津... 11月22日,京津冀律师驿站举办“党建业务深度融合 促进行业规范发展”主题活动,发布“百千万行动计划...
家装预付资金安全困局如何破解,... 家装预付资金安全困局如何破解 专家提出:建立“先验收后付款”装修资金存管制度 预交数万元甚至数十万元...
工行安康解放路支行积极开展《反... 为深入贯彻落实《国家金融监督管理总局安康监管分局办公室关于开展<反有组织犯罪法>宣传活动的通知》要求...
重庆公布育儿补贴制度实施方案 原标题:每孩每年3600元 重庆公布育儿补贴制度实施方案 11月21日,记者了解到,市卫生健康委、市...
十五运会组委会在深总结本届赛事... 深圳新闻网2025年11月22日讯(深圳报业集团记者 林炜航)11月21日,十五运会组委会在深圳市民...
中国军视网:日本妄言击沉福建舰... 本文转自【中国军视网】; 日本首相高市早苗发表涉台错误言论,公然挑战一个中国原则,甚至还有日本无知政...
重磅!东莞长安50万㎡产城发布... 在当下竞争激烈的市场环境中,中小企业如何突破成本压力,找到一片既能扎根成长又能眺望未来的理想栖息地?...
毕马威:政策、资本等多维着力 ... 由毕马威联合长三角G60科创走廊创新研究中心主办的“长三角高端装备新质领袖榜单发布仪式”于11月21...