1. 程式人生 > >重寫hashcode和equals方法,以及加入treeset實現comparable介面重寫compareTo方法

重寫hashcode和equals方法,以及加入treeset實現comparable介面重寫compareTo方法

package Interview;

import java.util.*;


class People implements Comparable<People> {
	public String name;
	public int age;

	public People(String name,int age) {
		this.name=name;
		this.age=age;
	}
	public int hashCode() {
		return Objects.hash(name, age);
	}

	public boolean equals(Object o) {
		if (!(o instanceof People)) {
			return false;
		}
		People p = (People) o;
		return age == p.age && name.equals(p.name);
	}
	
	//加入treeset必須實現comparable介面,重寫compare方法
	@Override
	public int compareTo(People o) {
		// TODO Auto-generated method stub
		People p = (People) o;
		if(this.age>p.age){
			return -1;
		}else if(this.age<p.age){
			return 1;
		}
		return 0;
	}
}

public class 重寫hashcode和equals方法 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		People p1=new People("zhangsan", 11);
		People p2=new People("zhangsan", 11);
		People p3=new People("lisi", 21);

		TreeSet<People>set=new TreeSet<>();
		set.add(p1);
		set.add(p2);
		set.add(p3);
		
		Iterator<People>iterator=set.iterator();
		while (iterator.hasNext()) {
			People temp=iterator.next();
			System.out.println("姓名:"+temp.name+",年齡"+temp.age);
		}
		//System.out.println(set.size());
	}

}