Java集合之四Set、HashSet、LinkedHashSet、TreeSet

Set

Set接口是Collection的子接口,set接口没有提供额外的方法。

Set 集合不允许包含相同的元素,最多允许一个null值,如果试把两个相同的元素加入同一个 Set 集合中,则添加操作失败。

Set 判断两个对象是否相同不是使用 == 运算符,而是根据 equals 方法。

Set集合是如何判断两个元素是否相等的?

是通过对象的hashCode()方法和equals()方法判断的。所以建议自定义类要重写hashCode()方法和equals()方法。

首先Set集合是通过哈希算法来存储元素的,当像Set中添加对象时,首先调用此对象所在类的hashCode()方法,计算此对象的哈希值,此哈希值决定了此对象在Set中存储的位置。若此位置没有对象存储,则直接把对象存储进来,如果此位置已经有一个对象了,则通过equals()方法比较这两个对象是否相同,如果不同则存储进去,如果相同则这个对象不能存储进Set里。所以我们重写hashCode()方法和equals()方法,还要保持这两个方法一致,即hashCode相同的对象equals也要相同。

Set 集合判断两个元素相等的标准:两个对象通过 hashCode() 方法比较相等,并且两个对象的 equals() 方法返回值也相等。

重写 hashCode() 方法的基本原则
在程序运行时,同一个对象多次调用 hashCode() 方法应该返回相同的值
当两个对象的 equals() 方法比较返回 true 时,这两个对象的 hashCode() 方法的返回值也应相等
对象中用作 equals() 方法比较的 Field,都应该用来计算 hashCode 值

下面是一个没有重写hashCode()方法和equals()方法的例子

public class Person {
	
	private String name;
	private int age;
	
	public Person(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;
	}
	

}

测试类

@Test
	public void testSet(){
		Set set = new HashSet();
		Person p1 = new Person("jack",10);
		Person p2 = new Person("jack",10);
		set.add(p1);
		set.add(p2);
		System.out.println(p1.hashCode());
		System.out.println(p2.hashCode());
		System.out.println(p1.equals(p2));
		System.out.println(set);
	}
输出结果

99550389
1598924227
false
[wya.j2se.oop.coll.Person@5ef04b5, wya.j2se.oop.coll.Person@5f4da5c3]
所以我们希望第二个对象不能存储进去的话就必须重写,现在的 hashCode()方法和equals()方法都是用的Object的方法。

现在重写hashCode()方法和equals()方法

public class Person {
	
	private String name;
	private int age;
	
	public Person(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() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

}
输出结果

3255510
3255510
true
[wya.j2se.oop.coll.Person@31acd6]
HashSet

HashSet集合内的元素是无序的,注意并不是随机性。它是按 Hash 算法来存储集合中的元素,因此具有很好的存取和查找性能。
HashSet 具有以下特点:
①不能保证元素的排列顺序
②HashSet 不是线程安全的,
如果需要多线程访问它的话,可以用 Collections.synchronizedSet 方法来包装它:

Set s = Collections.synchronizedSet(new HashSet(...));

③集合元素可以是 null

LinkedHashSet

LinkedHashSet 是 HashSet 的子类,不允许集合元素重复。LinkedHashSet 根据元素的 hashCode 值来决定元素的存储位置,但它同时使用链表维护元素的次序,这使得元素看起来是以插入顺序保存的。LinkedHashSet插入性能略低于 HashSet,但在迭代访问 Set 里的全部元素时有很好的性能。
TreeSet

TreeSet 是 SortedSet 接口的实现类,TreeSet 可以确保集合元素处于排序状态。

特点:①TreeSet里添加的元素必须是同一类型的。

           ②可以按照添加进集中中的元素的指定顺序遍历,如String类、包装类默认按照从小到大的顺序遍历。

           ③当像TreeSet内添加自定义类的对象时,可以有两种排序方法:1.自然排序2.定制排序

自然排序

TreeSet 会调用集合元素的 compareTo(Object obj) 方法来比较元素之间的大小关系,然后将集合元素按升序排列。如果试图把一个对象添加到 TreeSet 时,则该对象的类必须实现 Comparable 接口。实现 Comparable 的类必须实现 compareTo(Object obj) 方法,两个对象即通过 compareTo(Object obj) 方法的返回值来比较大小。

当需要把一个对象放入 TreeSet 中,重写该对象对应的 equals() 时,应保证与 compareTo(Object obj) 方法有一致的结果:如果两个对象通过 equals() 方法比较返回 true,则通过 compareTo(Object obj) 方法比较应返回 0,要求equals()方法和hashCode()方法和compareTo()方法保持一致。

public class Person implements Comparable {
	
	private String name;
	private Integer age;
	
	public Person(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((age == null) ? 0 : age.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (age == null) {
			if (other.age != null)
				return false;
		} else if (!age.equals(other.age))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	@Override
	public int compareTo(Object o) {
		if(o instanceof Person){
			Person p = (Person)o;
			int result = this.age.compareTo(p.getAge());
			if(result == 0){
				result = this.name.compareTo(p.getName());
			}
			return result;
		}
		return 0;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
	
	

}

测试类

@Test
	public void testTreeSet(){
		Set set = new TreeSet();
		set.add(new Person("jack",10));
		set.add(new Person("jack",20));
		set.add(new Person("abc",10));
		set.add(new Person("tom",15));
		set.add(new Person("abc",10));
		Iterator it = set.iterator();
		while(it.hasNext()){
			System.out.println(it.next());
		}
	}
输出结果

Person [name=abc, age=10]
Person [name=jack, age=10]
Person [name=tom, age=15]
Person [name=jack, age=20]
定制排序
TreeSet的自然排序是根据集合元素的大小,进行元素升序排列。如果需要定制排序,比如降序排列,可通过Comparator接口的帮助。需要重写compare(To1,T o2)方法。利用int compare(To1,T o2)方法,比较o1和o2的大小:如果方法返回正整数,则表示o1大于o2;如果返回0,表示相等;返回负整数,表示o1小于o2。要实现定制排序,需要将实现Comparator接口的实例作为形参传递给TreeSet的构造器。此时,仍然只能向TreeSet中添加类型相同的对象。否则发生ClassCastException异常。使用定制排序 判断两个元素相等的标准是:通过Comparator比较两个元素返回了0, 要求equals()方法和hashCode()方法和compareTo()方法保持一致。
public class Person {
	private Integer id;
	private String name;
	private Integer age;
	
	public Person(Integer id,String name, Integer age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}
	
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((age == null) ? 0 : age.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (age == null) {
			if (other.age != null)
				return false;
		} else if (!age.equals(other.age))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

}
@Test
	public void test1(){
		//创建一个实现Comparator接口的对象
		Comparator com = new Comparator() {
			//重写compare方法,定义Person类的排序规则,这里定义按id从小到大排序
			@Override
			public int compare(Object o1, Object o2) {
				if(o1 instanceof Person && o2 instanceof Person){
					Person p1 = (Person)o1;
					Person p2 = (Person)o2;
					return p1.getId().compareTo(p2.getId());
				}
				return 0;
			}
		};
		//把com对象当做形参传到TreeSet构造器中
		TreeSet set = new TreeSet(com);
		set.add(new Person(1,"jack",12));
		set.add(new Person(21,"jack",12));
		set.add(new Person(11,"jack",12));
		set.add(new Person(9,"jack",12));
		Iterator it = set.iterator();
		while(it.hasNext()){
			System.out.println(it.next());
		}
	}
输出结果
Person [id=1, name=jack, age=12]
Person [id=9, name=jack, age=12]
Person [id=11, name=jack, age=12]
Person [id=21, name=jack, age=12]

下面看一个加强版

定义一个Employee类,该类包含:private成员变量name,age,birthday,其中 birthday 为 MyDate 类的对象;定义一个MyDate类包含:private成员变量month,day,year;

分别按以下两种方式对集合中的元素进行排序,并遍历输出:

1). 使Employee实现Comparable 接口,并按 name 排序

2). 创建TreeSet 时传入 Comparator对象,按生日日期的先后排序。

注意:Employee类和MyDate类都要重写hashCode()方法和equals()方法
public class Employee implements Comparable<Employee>{
	
	private String name;
	private Integer age;
	private MyDate birthDay;
	
	public Employee(String name, Integer age, MyDate birthDay) {
		super();
		this.name = name;
		this.age = age;
		this.birthDay = birthDay;
	}
	@Override
	public String toString() {
		return "Employee [name=" + name + ", age=" + age + ", birthDay=" + birthDay + "]";
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public MyDate getBirthDay() {
		return birthDay;
	}
	public void setBirthDay(MyDate birthDay) {
		this.birthDay = birthDay;
	}
	@Override
	public int compareTo(Employee o) {
		return this.getName().compareTo(o.getName());
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((age == null) ? 0 : age.hashCode());
		result = prime * result + ((birthDay == null) ? 0 : birthDay.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Employee other = (Employee) obj;
		if (age == null) {
			if (other.age != null)
				return false;
		} else if (!age.equals(other.age))
			return false;
		if (birthDay == null) {
			if (other.birthDay != null)
				return false;
		} else if (!birthDay.equals(other.birthDay))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	

}
public class MyDate {
	
	private Integer year;
	private Integer month;
	private Integer day;
	
	public MyDate(Integer year, Integer month, Integer day) {
		super();
		this.year = year;
		this.month = month;
		this.day = day;
	}
	@Override
	public String toString() {
		return "MyDate [year=" + year + ", month=" + month + ", day=" + day + "]";
	}
	public Integer getYear() {
		return year;
	}
	public void setYear(Integer year) {
		this.year = year;
	}
	public Integer getMonth() {
		return month;
	}
	public void setMonth(Integer month) {
		this.month = month;
	}
	public Integer getDay() {
		return day;
	}
	public void setDay(Integer day) {
		this.day = day;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((day == null) ? 0 : day.hashCode());
		result = prime * result + ((month == null) ? 0 : month.hashCode());
		result = prime * result + ((year == null) ? 0 : year.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		MyDate other = (MyDate) obj;
		if (day == null) {
			if (other.day != null)
				return false;
		} else if (!day.equals(other.day))
			return false;
		if (month == null) {
			if (other.month != null)
				return false;
		} else if (!month.equals(other.month))
			return false;
		if (year == null) {
			if (other.year != null)
				return false;
		} else if (!year.equals(other.year))
			return false;
		return true;
	}
}

/**
	 * 使用自然排序 根据name排序
	 */
	@Test
	public void test2(){
		TreeSet<Employee> set = new TreeSet<Employee>();
		set.add(new Employee("abc", 12, new MyDate(2013, 10, 1)));
		set.add(new Employee("adc", 13, new MyDate(2013, 10, 1)));
		set.add(new Employee("jwbc", 23, new MyDate(2013, 10, 1)));
		set.add(new Employee("c2bc", 35, new MyDate(2013, 10, 1)));
		set.add(new Employee("wdabc", 55, new MyDate(2013, 10, 1)));
		set.add(new Employee("abc", 12, new MyDate(2013, 10, 1)));
		Iterator<Employee> it = set.iterator();
		while(it.hasNext()){
			System.out.println(it.next());
		}
	}

	/**
	 * 使用定制排序,根据生日先后排序
	 */
	@Test
	public void test3(){
		Comparator<Employee> com = new Comparator<Employee>() {

			/**
			 * 这样写排序规则后,相同的生日的Employee会插不进来,所以你也可以再加上判断name和age的规则
			 * 这里就只对生日进行排序了,TreeSet会先后调用compare方法、hashCode方法、equals方法来
			 * 判断插进来的对象是否存在于Set中。
			 * @param o1
			 * @param o2
			 * @return
			 */
			@Override
			public int compare(Employee o1, Employee o2) {
				MyDate birth1 = o1.getBirthDay();
				MyDate birth2 = o2.getBirthDay();
				if(!birth1.getYear().equals(birth2.getYear())){
					return birth1.getYear().compareTo(birth2.getYear());
				}else{
					if(!birth1.getMonth().equals(birth2.getMonth())){
						return birth1.getMonth().compareTo(birth2.getMonth());
					}else{
						return birth1.getDay().compareTo(birth2.getDay());
					}
				}
			}
		};
		
		TreeSet<Employee> set = new TreeSet<Employee>(com);
		set.add(new Employee("abc", 12, new MyDate(1913, 10, 1)));
		set.add(new Employee("adc", 13, new MyDate(2013, 8, 7)));
		set.add(new Employee("jwbc", 23, new MyDate(2000, 4, 23)));
		set.add(new Employee("c2bc", 35, new MyDate(1993, 1, 11)));
		set.add(new Employee("wdabc", 55, new MyDate(2017, 12, 9)));
		set.add(new Employee("abc", 12, new MyDate(2013, 11, 1)));
		set.add(new Employee("abc", 12, new MyDate(2013, 11, 1)));
		Iterator<Employee> it = set.iterator();
		while(it.hasNext()){
			System.out.println(it.next());
		}
	}


test2输出结果

Employee [name=abc, age=12, birthDay=MyDate [year=2013, month=10, day=1]]
Employee [name=adc, age=13, birthDay=MyDate [year=2013, month=10, day=1]]
Employee [name=c2bc, age=35, birthDay=MyDate [year=2013, month=10, day=1]]
Employee [name=jwbc, age=23, birthDay=MyDate [year=2013, month=10, day=1]]
Employee [name=wdabc, age=55, birthDay=MyDate [year=2013, month=10, day=1]]
test3输出结果

Employee [name=abc, age=12, birthDay=MyDate [year=1913, month=10, day=1]]
Employee [name=c2bc, age=35, birthDay=MyDate [year=1993, month=1, day=11]]
Employee [name=jwbc, age=23, birthDay=MyDate [year=2000, month=4, day=23]]
Employee [name=adc, age=13, birthDay=MyDate [year=2013, month=8, day=7]]
Employee [name=abc, age=12, birthDay=MyDate [year=2013, month=11, day=1]]
Employee [name=wdabc, age=55, birthDay=MyDate [year=2017, month=12, day=9]]








  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值