HashSet和HashMap的区别比较

HashSet 实现的Set接口,集合中不允许出现重复的值(如果重复会覆盖):

package com.wlf.base;

public class Person
{
      public Person(String name, int age)
        {
            this.name = name;
            this.age = age;
        }

        private String name;
        private int age;

        public String getName()
        {
            return name;
        }

        public void setName(String name)
        {
            this.name = name;
        }

        public int getAge()
        {
            return age;
        }

        public void setAge(int age)
        {
            this.age = age;
        }

        public String toString()
        {
            return "{" + name + ", " + age + "}";
        }

}
    public static void main(String[] args) 
    {
        Collection<Person> set = new HashSet<Person>();
        Person object = new Person("张三",22);
        set.add(new Person("李四", 19));
        set.add(new Person("王五", 22)); 
        set.add(object);
        object.setAge(34);
        set.add(object);
        print(set);
    }

    private static void print(Collection<Person> set)
    {
        Iterator<Person> it = set.iterator();
        while (it.hasNext())
        {
            Person p = it.next();
            System.out.println(p.toString());
        }
    }

输出结果是:
{张三, 34}
{李四, 19}
{王五, 22}

HashSet内部使用HashMap实现, 通过

  if (e.hash == hash && ((k = e.key) == key || key.equals(k)))来判断加入的元素是否相同。这里的hash是对象的hashCode,默认是通过地址计算的hashCode, 这里加入过的object相同,第二次加入的会覆盖前一次加入的

为了避免出现下面这种输出:

    public static void main(String[] args) 
    {
        Collection<Person> set = new HashSet<Person>();
        Person object = new Person("张三",22);
        set.add(new Person("李四", 19));
        set.add(new Person("王五", 22)); 
        set.add(new Person("张三",22));
        set.add(object);
        print(set);
    }

    private static void print(Collection<Person> set)
    {
        Iterator<Person> it = set.iterator();
        while (it.hasNext())
        {
            Person p = it.next();
            System.out.println(p.toString());
        }
    }

输出
{王五, 22}
{张三, 22}
{张三, 22}
{李四, 19}

输出了两个张三,这两个加入的对象不一样,本意是不想出现这种情况,所以在加入HashSet前需要重写HashCode和equals方法:
Person类增加重写方法:

    public int hashCode()
    {
        return name.hashCode() + age;
    }

    public boolean equals(Object obj)
    {
        if (!(obj instanceof Person))
            throw new ClassCastException("类型不匹配");
        Person p = (Person)obj;
        return this.name.equals(p.getName()) && this.age == p.getAge();
    }

HashMap 实现了Map接口,Map中不允许重复的 键值(如果重复会覆盖),HashMap中允许key和value为null

        //测试HashMap
        HashMap<Integer,Person> tmpMap = new HashMap<Integer,Person>();
        Integer intObj = new Integer(3);
        tmpMap.put(intObj, new Person("李四",14));
        tmpMap.put(intObj, new Person("李四",16));
        tmpMap.put(null, null);
        printMap(tmpMap);

hashMap的三种输出方法:

    private static void printMap(HashMap<Integer,Person> tmpHash)
    {
        //Iterator<Entry<Integer,Person>> result = tmpHash.entrySet().iterator();
        //1.通过Entry来遍历HashMap
        for(Entry<Integer,Person> result:tmpHash.entrySet())
        {
            System.out.println("key="+result.getKey()+"value="+result.getValue());
        }

        //2.通过KeySet来获取
        for(Integer key:tmpHash.keySet())
        {
            System.out.println("key="+key+"value="+tmpHash.get(key));
        }
        //3.通过entrySet的iterator来获取
        Iterator<Entry<Integer, Person>> it = tmpHash.entrySet().iterator();  
          while (it.hasNext()) {  
           Entry<Integer, Person> entry = it.next();  
           System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());  
          } 
    }

输出结果:key=nullvalue=null
key=3value={李四, 16}

HashMap是非线程安全的,但是Collection提供了方法转成线程安全:

 Map<Integer, Person> tmpMap = Collections.synchronizedMap(new HashMap<Integer,Person>());
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值