HashSetオブジェクトの重量除去

2635 ワード

import java.util.Set ;
import java.util.HashSet ;
class Person{
	private String name ;
	private int age ;
	public Person(String name,int age){
		this.name = name ;
		this.age = age ;
	}
	public boolean equals(Object obj){	//  equals, 
		if(this==obj){
			return true ;
		}
		if(!(obj instanceof Person)){
			return false ;
		}
		Person p = (Person)obj ;	//  
		if(this.name.equals(p.name)&&this.age==p.age){
			return true ;
		}else{
			return false ;
		}
	}
	public int hashCode(){
		return this.name.hashCode() * this.age	; //  
	}
	public String toString(){
		return " :" + this.name + "; :" + this.age ;
	}
};
public class RepeatDemo02{
	public static void main(String args[]){
		Set<Person> allSet = new HashSet<Person>() ;
		allSet.add(new Person(" ",30)) ;
		allSet.add(new Person(" ",31)) ;
		allSet.add(new Person(" ",32)) ;
		allSet.add(new Person(" ",32)) ;
		allSet.add(new Person(" ",32)) ;
		allSet.add(new Person(" ",33)) ;
		allSet.add(new Person(" ",33)) ;
		System.out.println(allSet) ;
	}
};

対象を重んずる
 
 
 
 
TreeSetソート
 
 
import java.util.Set ;
import java.util.TreeSet ;
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 toString(){
		return " :" + this.name + "; :" + this.age ;
	}
	public int compareTo(Person per){
		if(this.age>per.age){
			return 1 ;
		}else if(this.age<per.age){
			return -1 ;
		}else{
			return this.name.compareTo(per.name) ;	//  String compareTo() 
		}
	}
};
public class TreeSetDemo04{
	public static void main(String args[]){
		Set<Person> allSet = new TreeSet<Person>() ;
		allSet.add(new Person(" ",30)) ;
		allSet.add(new Person(" ",31)) ;
		allSet.add(new Person(" ",32)) ;
		allSet.add(new Person(" ",32)) ;
		allSet.add(new Person(" ",32)) ;
		allSet.add(new Person(" ",33)) ;
		allSet.add(new Person(" ",33)) ;
		System.out.println(allSet) ;
	}
};