Uchenna Nwanyanwu
Uchenna Nwanyanwu

Reputation: 3204

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?

Update

I want to be able to add MyObject1 and MyObject2 in the same map. Like

Map<Long, ? extends MyObject1> map;

so that i can do this

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

Hope it is clearer now.

Upvotes: 0

Views: 183

Answers (2)

Pau Kiat Wee
Pau Kiat Wee

Reputation: 9505

You can directly use Map<Long, MyObject1>:

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

Note:

? extends MyObject1 is a wildcard. It stands for "some unknown type, and the only thing we know about it is it's a subtype of Object". It's fine in the declaration but you can't instantiate it because it's not an actual type.

Upvotes: 3

tibtof
tibtof

Reputation: 7957

Let's assume the id is the key. It would be something like this:

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

Upvotes: 1

Related Questions