0

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.

Joarder Kamal
  • 1,387
  • 1
  • 20
  • 28
  • To store multiple values within a key you can refer to [HashMap with multiple values under the same key](http://stackoverflow.com/questions/4956844/hashmap-with-multiple-values-under-the-same-key) – Alvin Wong Jun 24 '13 at 13:37
  • [Java Tutorials: The Map Interface](http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html) – predi Jun 24 '13 at 13:39

5 Answers5

9
  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

Community
  • 1
  • 1
kosa
  • 65,990
  • 13
  • 130
  • 167
  • using HashMap now I am getting the following error: `HashMap cannot be resolved to a type` any suggestion, pls? – Joarder Kamal Jun 24 '13 at 13:38
  • 1
    @JoarderKamal:Make sure imports are there. – kosa Jun 24 '13 at 13:39
  • Just wondering, how can I now put multiple values using the Test class variables (I have 3 variables of different types in Test). Any guidance kindly? – Joarder Kamal Jun 24 '13 at 13:52
  • @JoarderKamal: I would suggest to add all 3 instances of Test to either ArrayList (or) HashSet etc., and add this collection to your map. – kosa Jun 24 '13 at 13:55
3

YOu can't instantiate an Interface.

Use HashMap on the righthand side

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
3

Map is an interface. You cannot instantiate an interface.

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

JHS
  • 7,761
  • 2
  • 29
  • 53
2

Do this:

Map<Timestamp, Test> map = new HashMap<Timestamp, Test>();
Ridcully
  • 23,362
  • 7
  • 71
  • 86
2

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>();

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • Thanks for the guide. No more error message now. Btw, I actually wanted to use multiple values of different types not a single Object (of different type). – Joarder Kamal Jun 24 '13 at 13:45