Set集合

Set集合 分支常有類 HashSet            TrreSet

Set裏沒有重複元素可以直接用來去重;

HashSet 通過比較對象的哈希碼判斷對象是否相同,可通過重寫Hash碼方法來改變對象Hash碼計算方法

    String類型Hash碼與內容有關,相同字符串Hash碼相同(內容相同,哈希姆一定相同,反之則不一定)(String裏重寫了Object裏HashCode 的計算方式,是通過字符內容計算的)

    Object 返回地址,通過地址計算哈希姆;

Hash碼可以減少判斷,計算快;

Hash碼相同可能是巧合(可能性低),所以需要equals方法進一步比較,出現相同,自動調用equals

HashSet(特點是 增刪效率高,但佔用空間大特點是 增刪效率高,但佔用空間大):

重寫hashCode方法:

class Student implements Comparable{
	private String name;
	private int age;
	
	public String getName(){
		return this.name;
	}
	
	public int getAge(){
		return this.age;
	}
	
	//重寫toString方法
	public String toString(){
		return "name="+name+",age="+age;
	}
	
	public Student(String name,int age){
		this.name=name;
		this.age=age;
	}
	//重寫hashCode方法
	public int hashCode(){
		return this.name.hashCode()+age;
	}
	//重寫equals方法
	public boolean equals(Object stu){
		Student s=null;
		if(stu instanceof Student){//判斷進來的stu是不是Student的實例或對象
			s=(Student)stu;//是就強轉爲Student類型
		}
		if(this.name.equals(s.getName())&&this.age==s.getAge()){
			return true;
		}else{
			return false;
		}
	}
	

	
	
}

TreeSet (沒有順序,不能重複,會自然排序(如儲存的是b,c ,a,輸出是a,b,c)):

當要把對象存入TreeSet集合時,會報錯,原因是不知道怎麼對對象進行排序;

此時需要自定義排序方法:當添加自定義的對象到TreeSet集合時

                                            必須自定義類實現Comparable接口,並實現裏面的compareTo抽象方法

                            當兩種排序方法都存在時,以比較器爲主

重寫compareTo()方法:

class Student implements Comparable{
	private String name;
	private int age;
	
	public String getName(){
		return this.name;
	}
	
	public int getAge(){
		return this.age;
	}
	
	//重寫toString方法
	public String toString(){
		return "name="+name+",age="+age;
	}
	
	public Student(String name,int age){
		this.name=name;
		this.age=age;
	}
	//重寫hashCode方法
	public int hashCode(){
		return this.name.hashCode()+age;
	}
	//重寫equals方法
	public boolean equals(Object stu){
		Student s=null;
		if(stu instanceof Student){//判斷進來的stu是不是Student的實例或對象
			s=(Student)stu;//是就強轉爲Student類型
		}
		if(this.name.equals(s.getName())&&this.age==s.getAge()){
			return true;
		}else{
			return false;
		}
	}
	

	//重寫compareTo方法
	public	int compareTo(Object s){
		Student stu=null;
		if(s instanceof Student){
			stu=(Student)s;
		}
		if(this.name.hashCode()==stu.getName().hashCode()){
			return 0;//表示重複
		}else if(stu.getName().hashCode()>this.name.hashCode()){
			return 1;//大的放前面
		}else{
			return -1;
		}
	
	} 	
	
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章