java:Set对象TreeSet有序子类,HashSet无序子类,重复对象二

TreeSet有序子类;

HashSet无序子类

重复重复元素,Object对象是通过equals和hashCode来进行过滤的。

如果将上一篇提到中的例子中的TreeSet,换成HashSet,那么代码就不会过滤从的对象

HashSet无序子类,如何过滤重复的对象呢?(单个元素是可以过滤,但相同的对象不会)

Person:

public class Person implements Comparable<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 String toString() {
		return "姓名:" + name + ", 年龄:" + age + "";
	}

	public int compareTo(Person o) {
		// TODO 自动生成的方法存根
		if(this.age > o.age)
		{
			return 1;
		}else if(this.age < o.age)
		{
			return -1;
		}else{
			//如果age年龄相同需要在判断name,是否重复
			return this.name.compareTo( o.name );
		}
	}
	
	
}

  

SetDemo3:

Set<Person> allSet = new HashSet<Person>();
		
		allSet.add(new Person("张三",30));
		//重复对象
		allSet.add(new Person("张三",30));
		allSet.add(new Person("李四",30));
		allSet.add(new Person("王五",31));
		allSet.add(new Person("赵六",31));
		allSet.add(new Person("田七",32));
		//重复对象
		allSet.add(new Person("田七",32));
		
		System.out.println(allSet);

输出结果:

[姓名:王五, 年龄:31, 姓名:田七, 年龄:32, 姓名:田七, 年龄:32, 姓名:张三, 年龄:30, 姓名:张三, 年龄:30, 姓名:李四, 年龄:30, 姓名:赵六, 年龄:31]

这时需要过滤掉重复的对象,那么Person还需要复写equels,和HashCode两个方法,这两个方法作用了过滤重复的对象:

public int hashCode()
	{
		return this.name.hashCode() * this.age;
	}
		
	public boolean equals(Object o)
	{
		if(this == o)
		{
			return true;
		}
		if( !(o instanceof Person) )
		{
			return false;
		}
		Person p = (Person) o;
		if(this.name.equals(p.name) && this.age == p.age)
		{
			return true;
		}else{
			return false;
		}
		
	}

  

执行的结果:

[姓名:赵六, 年龄:31, 姓名:李四, 年龄:30, 姓名:张三, 年龄:30, 姓名:王五, 年龄:31, 姓名:田七, 年龄:32]

  

原文地址:https://www.cnblogs.com/achengmu/p/7469856.html