DESKTOP-IL3AS1R_20200909-陈鑫

问题:

HashMap存储自定义类型键值

public class Trees {
    private String name;
    private int age;
    
    public Trees() {
    }
    
    public Trees(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( obj instanceof Trees ) {
            Trees p = (Trees)obj;
            System.out.println( "equals" );
            return name.equals( p.name ) && age == p.age ;
        }
        return false;
    }

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

测试类( TreesTest )

public class TreesTest {

    public static void main(String[] args) {
        Map<Trees,Integer> map = new HashMap<>();
        
        map.put(new Trees( "杨树", 28 ) , 100 );
        map.put(new Trees( "柳树", 50 ) , 50 );
        map.put(new Trees( "银杏树", 40 ) , 41 );
        map.put(new Trees( "梧桐树", 28 ) , 601 );
        map.put(new Trees( "松树", 15 ) , 116 );
        System.out.println(map);
        
        //获取Map集合中,所有的键值对(Entry)对象,以Set集合形式返回
        Set<Trees> keys = map.keySet();
        for(Trees name : keys) {
            System.out.println("(" + name +"," + map.get(name)+")");
        }
    }

}

当给HashMap中存放自定义对象时,如果自定义对象作为key存在,这时要保证对象唯一,必须重写对象的hashCode和equals方法

吐槽:

为祖国教育事业及国家铁路献上绵薄之力。

标签

© 2021 成都云创动力科技有限公司 蜀ICP备20006351号-1