java使用Set接口来描述集合,而Set中每一个数据元素都是唯一的。
HashSet散列集合Hash算法:把任意长度输入,通过散列算法,变换成固定长度的输出即散列值。对不同类型信息,散列值公式也是不完全相同的。
使用HashSet存储自定义类时,要重写equals和hashCode方法,以便在集合校验元素时(数据元素不允许重复),需要调用equals和hashCode验证(返回均为true)。
hashCode函数:
public int hashCode()返回该对象的哈希码值。在重写父类的equals方法时,也重写hashcode方法,使相等的两个对象获取的hashCode也相等,这样当此对象做Key时,两个equals为true的对象其获取的value都是同一个。
例如,对于元素类Student:
1classStudent{2publicString code;3publicString name;4publicStudent(String code,String name){5this.code =code;6this.name =name;7}8}
在此类中,假定使用code来判断元素是否重复,应添加重写后的equals和hashCode函数:
1publicbooleanequals(Object o){2if(this==o)3returntrue;4if(o.getClass() == Student.class){5Student s =(Student)o;6returns.code.equals(this.code);7}8returnfalse;9}1011publicinthashCode(){12returnthis.code.hashCode();13}
故而下面的例子,只会输出一组数据:First
1publicclassHashSetText{2publicstaticvoidmain(String args[]){3HashSet<Student>hs =newHashSet<Student>();4Student s1 =newStudent("1","First");5hs.add(s1);6Student s2 =newStudent("1","Second");7hs.add(s2);//此处,因为判断出1重复,故不会加入Second89Iteractor<Student>1 =hs.iterator();10while(i.hashNext()){11Student student =(Student) i.next();12System.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类的程序如下:
1publicclassHashMapToEntry{2publicstaticvoidmain(String[] args){3Map<Integer String> hMap =newHashMap<Integer,String>();4hMap.put(1,"a");5hMap.put(2,"b");6hMap.put(3,"c");78Set<Entry<Integer,String>> hSet =hMap.entrySet();9Iterator<Entry<Integer,String>> it =hSet.itetator();10while(it.hasNext()){11Entry<Integer,String> type = (Entry<Integer,String>) it.next();12intk =type.getKey();13String v =type.getValue();14System.out.println(k + "-" +v);15}16}17}
TreeMap树形映射:
TreeMap为有序映射关系,每对键key-值value遵循自然序列有序排列。当向TreeMap中插入新的数据元素时,TreeMap可能会重新排序,固元素在整个映射组中是不固定的。
当key为自定义类时,需要在自定义类中重写compareTo方法,以提供比对形式。