Set接口(集合)

Set集合跟List集合相比,它是无序的,没有索引,并且不能重复存储某一元素(Set集合也允许存入null元素,只是不能重复)即使是存入一个整数也是不能重复的。

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Demo {
	
	public static void main(String[] args) {
		Set set = new HashSet<>();
		set.add("1");
		set.add("2");
		set.add(3);
		Iterator setIterator = set.iterator();
		while(setIterator.hasNext()) {
			System.out.println(setIterator.next());
		}
		
		System.out.println(set.size());//3
		System.out.println(set.remove("1"));//true
		System.out.println(set.contains("1"));//false
		set.clear();
		System.out.println(set.isEmpty());//true
		
		set.add("1");
		set.add("1");//连续两次存入整数1,但实际上只有第一次才能成功。
		System.out.println(set.size());
	}
}

其中,add,remove,contains方法均可简化为三目运算符理解。
1.add(Object o):向Set集合中添加元素,不允许添加重复数据。当且仅当Set集合中没有包含满足(o ==null ? e ==null : o.equals(e))条件的元素e时才能将元素o添加到集合中。
2.remove(Object o) : 删除Set集合中的obj对象,删除成功返回true,否则返回false。当且仅当Set集合中包含满足(o ==null ? e ==null : o.equals(e))条件的元素e时才能返回true。
3.contains(Object o):判断集合中是否包含obj元素。当且仅当Set集合中包含满足(o ==null ? e ==null : o.equals(e))条件的元素e时才返回true。

这三个方法其实并没有什么差别,都是多次使用hashCode方法和equals方法遍历判断。
HashSet集合对象判断数据元素是否重复时:先检查待存对象hashCode值是否与集合中已有元素对象hashCode值相同,如果hashCode不同则表示不重复, 如果hashCode相同再调用equals方法进一步检查,equals返回真表示重复,否则表示不重复。

发布了74 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/naruhina/article/details/87928048
今日推荐