HashMap集合存放自定义对象

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

class People {
    private String name;
    private int age;

    public People(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        People other = (People) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

    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;
    }

    @Override
    public String toString() {
        return "People [name=" + name + ", age=" + age + "]";
    }
}

class HashMapDemo {
    public static void main(String[] args) {
        HashMap hm = new HashMap();
        hm.put(new People("lishuai", 22), 22);
        hm.put(new People("liqian", 22), 21);
        hm.put(new People("mahongmei", 22), 51);
        hm.put(new People("lishuai", 22), 22);
        Set s = hm.keySet();
        for (Iterator iterator = s.iterator(); iterator.hasNext();) {
            Object key = iterator.next();
            Object value = hm.get(key);
            System.out.println(key + "======" + value);
        }
    }
}

HashMap的底层也是哈希表,由于是哈希表所以不保证存取有序,也是不同步的。HashMap中的哈希值是作用在key上的。为避免重复元素也就要求复写hashcode,equals方法。

    原文作者:李霖神谷
    原文地址: https://www.jianshu.com/p/e6c2ab3225c5
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞