Map自定义键时注意事项

public static void main(String[] args) {

        /*
         * 1.Map的键是String,Integer等类的话,就会重写HashCode()和equals()方法,
         *   键的值一样,后面的就会覆盖前面的
         */
        Map<Integer,String> map1 = new HashMap<>();
        map1.put(0,"a");
        map1.put(1,"b");
        map1.put(2,"c");
        map1.put(2,"d");
        System.out.println(map1.toString());
        System.out.println("#####################");


        /*
         * 2.键是自定义类的话,需要在自定义类中重写HashCode()和equals()方法,
         *   否则就算键的值一样,也会加进去的。
         */
        // 2.1未定义了hashcode和equals的属性作为键
        Map<User,String> map2 = new HashMap<>();
        map2.put(new User("jalen","123456"),"a");
        map2.put(new User("abely","123456"),"b");
        map2.put(new User("mercy","123456"),"c");
        map2.put(new User("jermy","123456"),"d");
        map2.put(new User("jermy","123456"),"e");
        for(User user : map2.keySet())
        {
            System.out.println(user.toString()+":"+map2.get(user));
        }
        System.out.println("#####################");


        // 2.1 定义了hashcode和equals的属性作为键
        Map<Manager,String> map3 = new HashMap<>();
        map3.put(new Manager("jalen","123456"),"aa");
        map3.put(new Manager("abely","123456"),"bb");
        map3.put(new Manager("mercy","123456"),"cc");
        map3.put(new Manager("jermy","123456"),"dd");
        map3.put(new Manager("jermy","123456"),"ee");
        for (Manager manager: map3.keySet()) {
            System.out.println(manager.toString()+":"+map3.get(manager));
        }

    }

运行结果:

{0=a, 1=b, 2=d}
#####################
User(username=jermy, password=123456):d
User(username=mercy, password=123456):c
User(username=jermy, password=123456):e
User(username=jalen, password=123456):a
User(username=abely, password=123456):b
#####################
Manager(managerName=jalen, managerPassword=123456):aa
Manager(managerName=abely, managerPassword=123456):bb
Manager(managerName=mercy, managerPassword=123456):cc
Manager(managerName=jermy, managerPassword=123456):ee

附录:User实体和Manager实体

import lombok.AllArgsConstructor;
import lombok.ToString;

@AllArgsConstructor
@ToString
public class User {

    private String username;

    private String password;

}
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Manager {

    private String managerName;

    private String managerPassword;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jalen备忘录

谢谢~~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值