package com.hu.cool;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import org.junit.Test;
public class Hashset {
/*
* 哈希算法
* 在像Set中添加對象的時候首先對用該對象的hashcode()方法計算出該對象的hashcode值
* 此值決定了對象在set中的存貯位置若位置已經存在對象;則需要調用equals方法來進行比較
* 如果相同則后一個不再插入進去。
*/
@Test
public void test() {
HashSet hashSet=new HashSet<>();
hashSet.add(234);
hashSet.add(new String("AA"));
hashSet.add(456);
hashSet.add("BB");
hashSet.add(null);
Person person=new Person("yongyuan", 14);
Person person2=new Person("yongyuan", 14);
//在進行是否相同的判斷的時候必須重寫equals()和hashcode()方法
//而List的時候只需要重寫equals方法就可以。
hashSet.add(person);
hashSet.add(person2);
System.out.println(hashSet.size());
System.out.println(hashSet);
}
@Test
public void Linkedhashset(){
Set set=new LinkedHashSet<>();
set.add(234);
set.add(456);
set.add("aa");
set.add("bb");
set.add(null);
Person person=new Person("yongyuan", 14);
Person person2=new Person("yongyuan", 14);
set.add(person2);
set.add(person);
System.out.println(set.size());
System.out.println(set);
}
//有序還是無序是針對存儲而不是遍歷,遍歷的時候都是有序的
//linkedhashset 插入的時候性能要地獄hashset但是迭代遍歷的時候性能明顯要比較高
@Test
public void TreeSet(){
/*//set.add("aa");添加的類型必須和之前的兼容不然會報錯
* 遍歷的時候沒有按照添加的順序排列而是按照字母的順序進行排序
*
*/
Set set=new java.util.TreeSet();
/*set.add("AA");
set.add("AA");
set.add("ABB");
set.add("GG");
set.add("MM");
set.add("KKA");
*/
//添加自定義類的時候需要重寫comparable接口
//進行插入的時候只要是有屬性值不一樣就不能插入,只能插入第一個當然可以自己寫comparable實現的方法來改寫
set.add(new Person("GG", 34));
set.add(new Person("AA", 24));
set.add(new Person("BB", 34));
set.add(new Person("JJ", 34));
System.out.println(set.size());
for (Object object : set) {
System.out.println(object);
}
}
}
**************************************************************************
Treeset的定制排序的方法
@Test
public void test3(){
//實現了一個叫comparatoe的對象
Comparator comparator=new Comparator() {
@Override
//在Treeset中創建custoer對象,並指明按照customer的那個屬性來進行比較排序
public int compare(Object o1, Object o2) {
if(o1 instanceof Customer && o2 instanceof Customer){
Customer customer1=(Customer) o1;
Customer customer2=(Customer) o2;
//下面這段代碼可以保證當比較的屬性相同的時候可以用其他屬性來進行比較。
int i= customer1.getAgeInteger().compareTo(customer2.getAgeInteger());
if(i==0){
return customer1.getNameString().compareTo(customer2.getNameString());
}else{
return i;
}
}
return 0;
}
};
//將次對象作為形參傳遞給treeset 對象
java.util.TreeSet set=new java.util.TreeSet(comparator);
//向Treeset中添加Comparator接口中compare方法中實現的對象
set.add(new Customer("AA", 1003));
set.add(new Customer("BB", 1001));
set.add(new Customer("CC", 1007));
set.add(new Customer("DD", 1003));
set.add(new Customer("EE", 1006));
for (Object object : set) {
System.out.println(object);
}
}