HashSet与HashMap的区别,你知道吗?

HashSet是通过HashMap实现的,TreeSet是通过TreeMap实现的,只不过Set用的只是Map的keyMap的key和Set都有一个共同的特性就是集合的唯一性.TreeMap更是多了一个排序的功能.hashCode和equal()是HashMap用的, 因为无需排序所以只需要关注定位和唯一性即可. a. hashCode是用来计算hash值的,hash值是用来确定hash表索引的. b. hash表中的一个索引处存放的是一张链表, 所以还要通过equal方法循环比较链上的每一个对象 才可以真正定位到键值对应的Entry. c. put时,如果hash表中没定位到,就在链表前加一个Entry,如果定位到了,则更换Entry中的value,并返回旧value由于TreeMap需要排序,所以需要一个Comparator为键值进行大小比较.当然也是用Comparator定位的. a. Comparator可以在创建TreeMap时指定 b. 如果创建时没有确定,那么就会使用key.compareTo()方法,这就要求key必须实现Comparable接口. c. TreeMap是使用Tree数据结构实现的,所以使用compare接口就可以完成定位了.

用法如下:

public class TestHashSet{//java 中Set的使用(不允许有重复的对象):public static void main(String[] args){HashSet hashSet=new HashSet();String a=new String("A");String b=new String("B");String c=new String("B");hashSet.add(a);hashSet.add(b);System.out.println(hashSet.size());String cz=hashSet.add(c)?"此对象不存在":"已经存在";System.out.println("测试是否可以添加对象 "+cz);System.out.println(hashSet.isEmpty());//测试其中是否已经包含某个对象System.out.println(hashSet.contains("A"));Iterator ir=hashSet.iterator();while(ir.hasNext()){System.out.println(ir.next());}//测试某个对象是否可以删除System.out.println(hashSet.remove("a"));System.out.println(hashSet.remove("A"));//经过测试,如果你想再次使用ir变量,必须重新更新以下ir=hashSet.iterator();while(ir.hasNext()){System.out.println(ir.next());}}}/** * 通过这个程序,还可以测试树集的添加元素的无序性与输出的有序性 */ import java.util.TreeSet;import java.util.Iterator;public class TreeSetTest{public static void main(String[] args){TreeSet tree = new TreeSet();tree.add("China");tree.add("America");tree.add("Japan");tree.add("Chinese");Iterator iter = tree.iterator();while(iter.hasNext()){System.out.println(iter.next());}}}

,千万个不眠的夜里,你一直让我感动,只是因为相信有个人会爱我一生一世。

HashSet与HashMap的区别,你知道吗?

相关文章:

你感兴趣的文章:

标签云: