java验证 Map 的 key、value 是否可以为空

1、验证示例代码

        Map<String, Object> maps = new HashMap<>();
        maps.put("a", "1");
        maps.put(null, null);
        maps.put("c", null);
        System.out.println("maps = " + maps);
        Object o = maps.get(null);
        System.out.println("o = " + o);

2、输出

maps = {null=null, a=1, c=null}
o = null

小结:
1、从结果看,Map中 key 可以为 null
2、Map中 value 也可以为 null
3、Map中 key、value 也可以同时为 null

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的Java代码示例,将两个自定义对象类型的List合并为一个Map,其中集合A作为key,集合B作为value: ```java import java.util.*; public class MergeListsToMap { public static void main(String[] args) { // Create two custom object type lists List<Person> personList = new ArrayList<>(); personList.add(new Person("Alice", 25)); personList.add(new Person("Bob", 30)); List<Address> addressList = new ArrayList<>(); addressList.add(new Address("123 Main St", "Anytown", "USA")); addressList.add(new Address("456 Elm St", "Othertown", "USA")); // Merge the lists into a map Map<List<Person>, List<Address>> map = new HashMap<>(); map.put(personList, addressList); // Print out the map System.out.println(map); } } class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } class Address { private String street; private String city; private String country; public Address(String street, String city, String country) { this.street = street; this.city = city; this.country = country; } public String getStreet() { return street; } public String getCity() { return city; } public String getCountry() { return country; } } ``` 在这个示例中,我们创建了两个自定义对象类型的List,一个是Person对象的列表,另一个是Address对象的列表。我们使用HashMap将这两个列表合并为一个Map,其中Person列表作为键,Address列表作为值。最后,我们打印出这个Map验证是否正确合并了两个列表。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值