Joarder Kamal
Joarder Kamal

Reputation: 1397

Store multiple values (of different types) under a same key using 'Map' in Java

I am trying to instantiate a map structure with the following

Map<Timestamp, Test> map = new Map<Timestamp, Test>();

where Test is a class with 3 different types of variables and Timestamp is a java.sql.Timestamp type.

But I am getting the following error

Can not instantiate type Map<Timestamp, Test>

My primary objective is to create a map structure where I can store multiple values/objects (of different types) from a Class implementation under the same timestamp key.

Upvotes: 0

Views: 1231

Answers (5)

kosa
kosa

Reputation: 66677

  1. Map<Timestamp, Test>

    You can't instantiate Map because it is interface. You need to do use one of the implementations like HashMap.

  2. You can't store multiple values in HashMap, for same Key unless values are either collection of objects (or) array. Another alternative is Google MultiMap

Upvotes: 9

Juned Ahsan
Juned Ahsan

Reputation: 68715

Do this

Map<Timestamp, Test> map = new HashMap<Timestamp, Test>();

instead of

Map<Timestamp, Test> map = new Map<Timestamp, Test>();

as you cannot instantiate the interface Map

The other thing you have mentioned that you want to store the values of different types, so use Object as the value instead of Test:

    Map<Timestamp, Object> map = new HashMap<Timestamp, Object>();

Upvotes: 2

Ridcully
Ridcully

Reputation: 23665

Do this:

Map<Timestamp, Test> map = new HashMap<Timestamp, Test>();

Upvotes: 2

JHS
JHS

Reputation: 7871

Map is an interface. You cannot instantiate an interface.

You need to use a class that implements the Map interface. Have a look here.

Upvotes: 3

NimChimpsky
NimChimpsky

Reputation: 47310

YOu can't instantiate an Interface.

Use HashMap on the righthand side

Upvotes: 3

Related Questions