前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java.util.Collection Set API

java.util.Collection Set API

原创
作者头像
HLee
修改2021-09-09 10:40:07
3060
修改2021-09-09 10:40:07
举报
文章被收录于专栏:房东的猫房东的猫房东的猫

简介

java.util.Collection 是一个集合框架的父接口。它提供了对集合对象进行基本操作的通用接口方法。Collection接口在Java 类库中有很多具体的实现。不能存储相同的元素,同时因为其是一个抽象的接口:所以不能直接实例化一个set对象。(Set s = new Set() )错误。该接口主要继承于Collection接口,所以具有Collection的一些常见的方法。

 Set<String> testSet = new HashSet<>();
 Set<Integer> test = new TreeSet<>();

add

描述:添加元素到Collection集合中。

boolean add(E e)

描述:将指定c中的所有元素都添加到此Collection集合中。

boolean addAll(Collection<? extends E> c)

clear

描述:移除此collection集合中的所有元素

void clear()

contains

描述:检查Collection集合中是否包含o对象,如果包含则返回true,否则返回false。

boolean contains(Object o)

描述:检查Collection集合中是否包含c的全部对象,全部包含则返回true,否则返回false。

boolean containsAll(Collection<?> c)

isEmpty

描述:检查Collection集合是否包含有元素,如果没有包含元素,则返回true,否则返回false。

boolean isEmpty()

iterator  

描述:返回在此collection集合的元素上进行迭代的迭代器。注意:迭代过程中不能用集合里的添加、删除等方法修改集合,不然会报错。

Iterator<E> iterator()

remove

描述:从collection集合中删除指定的元素,如果集合中有这个元素,并且删除成功,那么就返回true,否则返回false。

boolean remove(Object o)

描述:从集合中删除c集合中所有的元素。

boolean removeAll(Collection<?> c)

size     

描述:返回集合中元素个数。

int size()

equals

描述:比较此collection集合与指定对象是否相等,是比较的是里面元素是否相等,而不是比较地址是否相等。

boolean equals(Object o)

retainAll

描述:集合中仅保留c集合中的所有元素

boolean retainAll(Collection<?> c)

toArray

描述:返回包含此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 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简介
  • add
  • clear
  • contains
  • isEmpty
  • iterator  
  • remove
  • size     
  • equals
  • retainAll
  • toArray
  • 工具方法
    • 元素去重
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档