HashMap和HashSet

Java使用Set接口来描述集合,而Set中每一个数据元素都是唯一的。

HashSet散列集合

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散列图

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方法,以提供比对形式。

————————————————————————————————————————————————
来自企鹅娘的问候:
欢迎交流哦,如果有帮助转载的话,请务必注明出处"企鹅娘's 学习笔记",让我也小小的开心一下
原文地址:https://www.cnblogs.com/hopecapital/p/4814790.html