java.util.Collection 是一个集合框架的父接口。它提供了对集合对象进行基本操作的通用接口方法。Collection接口在Java 类库中有很多具体的实现。不能存储相同的元素,同时因为其是一个抽象的接口:所以不能直接实例化一个set对象。(Set s = new Set() )错误。该接口主要继承于Collection接口,所以具有Collection的一些常见的方法。
Set<String> testSet = new HashSet<>();
Set<Integer> test = new TreeSet<>();
描述:添加元素到Collection集合中。
boolean add(E e)
描述:将指定c中的所有元素都添加到此Collection集合中。
boolean addAll(Collection<? extends E> c)
描述:移除此collection集合中的所有元素
void clear()
描述:检查Collection集合中是否包含o对象,如果包含则返回true,否则返回false。
boolean contains(Object o)
描述:检查Collection集合中是否包含c的全部对象,全部包含则返回true,否则返回false。
boolean containsAll(Collection<?> c)
描述:检查Collection集合是否包含有元素,如果没有包含元素,则返回true,否则返回false。
boolean isEmpty()
描述:返回在此collection集合的元素上进行迭代的迭代器。注意:迭代过程中不能用集合里的添加、删除等方法修改集合,不然会报错。
Iterator<E> iterator()
描述:从collection集合中删除指定的元素,如果集合中有这个元素,并且删除成功,那么就返回true,否则返回false。
boolean remove(Object o)
描述:从集合中删除c集合中所有的元素。
boolean removeAll(Collection<?> c)
描述:返回集合中元素个数。
int size()
描述:比较此collection集合与指定对象是否相等,是比较的是里面元素是否相等,而不是比较地址是否相等。
boolean equals(Object o)
描述:集合中仅保留c集合中的所有元素
boolean retainAll(Collection<?> c)
描述:返回包含此collection集合中所有元素的数组
Object[] toArray()
public class SetRemo {
public static void main(String[] args) {
HashSet hs=new HashSet<>();
hs.add(new Student("a","12"));
hs.add(new Student("b", "12"));
hs.add(new Student("c", "13"));
hs.add(new Student("c","12"));
hs.add(new Student("a","12"));
for (Object obj : hs) {
if(obj instanceof Student) {
Student stu=(Student)obj;
System.out.println(stu.getName() + stu.getAge());
}
}
}
}
@Getter
@Setter
class Student{
private String name;
private String age;
public Student(String name, String age) {
this.name = name;
this.age = age;
}
public Student() {}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return this.getName().hashCode()+this.getAge().hashCode();
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Student) {
Student s=(Student)obj;
return this.getName().equals(s.getName()) && this.getAge().equals(s.getAge());
}
return false;
}
}
备注: HashSet去重时自动调用hashCode()方法,这个方法会返回一个哈希值,只有当这个哈希值相等时才会调用equals()方法进行去重。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。