集合框架3:Set集合

本文深入讲解Java中Set集合的使用方法,包括HashSet如何确保元素唯一性及TreeSet如何对元素进行排序。通过具体实例演示了两种集合的特点及其应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Set集合
   
Set(集,为接口)
Set集合的功能(方法)和Collection是一致的
注意:add()返回的值是布尔类型。
手痒:把Collection的用法练了下:
package 优快云.review;
import java.util.*;
//集合类在util包下
public class Collection {

	public static void main(String[] args) {
		//因为Collection是接口,只能创建他的子类的实例
		ArrayList<String> list= new ArrayList<String>();
		//添加元素
		list.add("Collection1");
		list.add("Collection2");
		list.add("Collection3");
		list.add("Collection4");
		//可以直接打印,应该重谢了toString方法,直接看到其中的元素
		System.out.println(list.contains("Collection1"));
/*		list.clear();清空集合中所有元素*/
		System.out.println(list.size());
		//集合中有几个元素
		list.remove(0);
		//移除第几个袁术
		System.out.println(list);
		
		ArrayList<String> list2= new ArrayList<String>();
		list2.add("Collection3");
		list2.add("Collection4");
		list2.add("Collection5");
		list2.add("Collection6");
		
//		list.addAll(list2);
		//将集合list2中所有的元素添加到集合list中
		System.out.println(list.retainAll(list2));
		//list集合只保留和list2集合中也含有的元素
//		list.removeAll(list2);
		//list集合去掉集合list2中包含的元素
		System.out.println(list);
		System.out.println(list2);
		System.out.println(list2.contains("Collection3"));
	}
}
1.HashSet
底层数据结构式哈希表;
HashSet是如何保证元素的唯一性呢?
是通过元素的两个方法(注意是元素哦),hashCode()和equals()来完成的:
如果元素的HashCode值相同,才会判断equals的值是否为true
如果元素的HashCode值不同,不会调用equals方法。
package 优快云.review;
import java.util.*;
public class HashSetDemo {

	/**
	 * @param args
	 * HushSet的元素是无序和不重复的
	 */
	public static void sop(Object obj){
		System.out.println(obj);
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HashSet hs= new HashSet<>();
		
		sop(hs.add("java1"));
		sop(hs.add("java1"));//注意add方法的返回值
		hs.add("java2");
		hs.add("java3");
		hs.add("java4");
		
		Iterator it = hs.iterator();
		while(it.hasNext())
		{
			sop(it.next());
		}
		
	}

}
例子比较简单,来个难一点的:
package 优快云.review;
import java.util.*;
public class HashSetTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HashSet hs= new HashSet<>();
		hs.add(new Person2("zhangsan",20));
		hs.add(new Person2("zhangsan2",21));
		hs.add(new Person2("zhangsan3",23));
		
		System.out.println(hs);
		hs.add(new Person2("zhangsan2",21));
		System.out.println(hs);
		Person2 p= new Person2("zhangsan", 20);
		if(hs.contains(p))
			hs.remove(p);
		System.out.println(hs);
	}

}
class Person2{
	private String name;
	private int age;
	
	Person2(){}
	Person2(String name,int age){
		this.name=name;
		this.age=age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override 	
	public int hashCode(){
		return this.name .hashCode()+this.age;
	}
	@Override 	
	public boolean equals(Object obj){
		if(!(obj instanceof Person2))
		   return false;
		Person2 p =(Person2)obj;
		
		return this.name.equals(p.name)&&this.age==p.age;
	}
		
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
}
特地没加注释,知道干啥的不?

注意:对应判断元素是否存在以及删除等操作,依赖的方法还是元素的hashCode和equals方法。

2.TreeSet
可以对Set集合中的元素进行排序(默认自然顺序,没法排的话报错)
在存储实例时,对应的类必须实现Comparable接口,重写ComparaTo()方法,主要属性比较完后,比较次要条件,不然会出现只要主要条件相同则为同一个实例的情况,如都为18岁的学生是一个学生,显然不科学啊!
注:String类已经实现Comparable接口,在TreeSet里可劲造!
package day15.集合框架3;
import  java.util.*;
public class TreeSetDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		TreeSet ts= new TreeSet<>();
		ts.add("abc");
		ts.add("a1");
		ts.add("bc");
		ts.add("cas");
		ts.add("B");
		//n
		Iterator it = ts.iterator();
		while(it.hasNext())
		System.out.println(it.next());
		
	}

}
再来一普通实例的应用,跟前面的一样:
package day15.集合框架3;
import java.util.*;
public class TreeSetTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeSet<Student> ts =new TreeSet<>();
		ts.add(new Student("zhangsan",19));
		ts.add(new Student("lisi",20));
		ts.add(new Student("wangwu",22));
	    ts.add(new Student("zhuliu",20));
		System.out.println(ts);
	}

}
class Student implements Comparable
{
	private String name;
	private int age;
	Student(){}
	
	Student(String name, int age){
		this.name=name;
		this.age=age;
	}
	
	public String getName(){
		return this.name;
	}
	
	public int getAge(){
		return this.age;
	}
	@Override
	public String toString(){
		return "Student(name:"+name+",age:"+age+")";
	}
	
	public int hashCode(){
		return this.name.hashCode()+this.age*10;
	}
	
	
	@Override
	public int compareTo(Object o) {
		// TODO Auto-generated method stub
		if(!(o instanceof Student))
			throw new RuntimeException("not student !");
		Student s= (Student)o;
		if(this.age>s.age)
		return 1;
		if(this.age==s.age)
		{
			return this.name.compareTo(s.name);
		}
			//return 0;
			return -1;
	}
}

谢谢!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值