简体   繁体   English

如何使用泛型向Java Map添加相同的对象类型

[英]How to add the same object type to java Map using generics

I have two objects as follows 我有两个对象,如下所示

public class MyObject1 implements Serializable
{

private Long id;
... other properties and getters and setters
}

public class MyObject2 extends MyObject1
{
private String name;
...other properties and getters and setters
}

MyObject1 obj1 = new MyObject1();
MyObject2 obj2 = new MyObject2();

How do i add these two instances in a HashMap using generics? 如何使用泛型在HashMap中添加这两个实例?

Update 更新

I want to be able to add MyObject1 and MyObject2 in the same map. 我希望能够在同一张地图中添加MyObject1和MyObject2。 Like 喜欢

Map<Long, ? extends MyObject1> map;

so that i can do this 这样我就可以做到

map.put(obj1);
map.put(obj2);

Hope it is clearer now. 希望现在更加清楚。

You can directly use Map<Long, MyObject1> : 您可以直接使用Map<Long, MyObject1>

Map<Long, MyObject1> map = new HashMap<Long, MyObject1>();
map.put(1l, new MyObject1());
map.put(2l, new MyObject2());

Note: 注意:

? extends MyObject1 ? extends MyObject1 is a wildcard. ? extends MyObject1是一个通配符。 It stands for "some unknown type, and the only thing we know about it is it's a subtype of Object". 它代表“某种未知类型,我们唯一了解的是它的Object的子类型”。 It's fine in the declaration but you can't instantiate it because it's not an actual type. 在声明中没问题,但是您不能实例化它,因为它不是实际的类型。

Let's assume the id is the key. 假设id是密钥。 It would be something like this: 就像这样:

Map<Long, MyObject1> map = new HashMap<Long, MyObject1>();
map.add(obj1.getId(), obj1);
map.add(obj2.getId(), obj2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM