java使用Set接口來描述集合,而Set中每一個數據元素都是唯一的。
Hash算法:把任意長度輸入,通過散列算法,變換成固定長度的輸出即散列值。對不同類型信息,散列值公式也是不完全相同的。
使用HashSet存儲自定義類時,要重寫equals和hashCode方法,以便在集合校驗元素時(數據元素不允許重復),需要調用equals和hashCode驗證(返回均為true)。
hashCode函數:
public int hashCode()返回該對象的哈希碼值。在重寫父類的equals方法時,也重寫hashcode方法,使相等的兩個對象獲取的hashCode也相等,這樣當此對象做Key時,兩個equals為true的對象其獲取的value都是同一個。
例如,對于元素類Student:
1 class Student{2 public String code;3 public String name;4 public Student(String code,String name){5 this.code = code;6 this.name = name;7 }8 }
在此類中,假定使用code來判斷元素是否重復,應添加重寫后的equals和hashCode函數:
1 public boolean equals(Object o){ 2 if(this == o) 3 return true; 4 if(o.getClass() == Student.class){ 5 Student s = (Student)o; 6 return s.code.equals(this.code); 7 } 8 return false; 9 }10 11 public int hashCode(){12 return this.code.hashCode();13 }
故而下面的例子,只會輸出一組數據:First
1 public class HashSetText{ 2 public static void main(String args[]){ 3 HashSet<Student>hs = new HashSet<Student>(); 4 Student s1 = new Student("1","First"); 5 hs.add(s1); 6 Student s2 = new Student("1","Second"); 7 hs.add(s2);//此處,因為判斷出1重復,故不會加入Second 8 9 Iteractor<Student>1 = hs.iterator();10 while(i.hashNext()){11 Student student = (Student) i.next();12 System.out.PRintln(student);13 }14 }15 }
關于Iterator可以看這里:Java學習之Iterator(迭代器)的一般用法
Java使用Map接口描述映射結構,描述鍵key-值value的對應關系,Map不允許鍵重復,且每個鍵只能對應一個值。
Hashmap通過hash算法排布存儲Map中的鍵(key),數據元素成對出現一一對應(key-value)。
HashMap內存模式并不是連續的,key值的排布根據Hash算法獲得,檢索速度較快。HashMap將所有鍵key裝入迭代器遍歷,或使用Entry類,將所有元素轉化成Entry的集合進行處理。
將Map轉化為Entry類的程序如下:
1 public class HashMapToEntry{ 2 public static void main(String[] args){ 3 Map<Integer String> hMap = new HashMap<Integer,String>(); 4 hMap.put(1,"a"); 5 hMap.put(2,"b"); 6 hMap.put(3,"c"); 7 8 Set<Entry<Integer,String>> hSet = hMap.entrySet(); 9 Iterator<Entry<Integer,String>> it = hSet.itetator();10 while(it.hasNext()){11 Entry<Integer,String> type = (Entry<Integer,String>) it.next();12 int k = type.getKey();13 String v = type.getValue();14 System.out.println(k + "-" + v);15 }16 }17 }
TreeMap樹形映射:
TreeMap為有序映射關系,每對鍵key-值value遵循自然序列有序排列。當向TreeMap中插入新的數據元素時,TreeMap可能會重新排序,固元素在整個映射組中是不固定的。
當key為自定義類時,需要在自定義類中重寫compareTo方法,以提供比對形式。
新聞熱點
疑難解答