46
Map<String, ArrayList<Pair<String, Integer>>> k = new  Map<String, ArrayList<Pair<String, Integer>>>();

This line is in my code. I'd like to instantiate a Map that contains a String then an ArrayList of Pairs of Strings and Integers.

Pair is a class that I wrote that is in my package.

I get "Cannot Instantiate the type Map>>();

Why not? Seems reasonable to me...

PinkElephantsOnParade
  • 6,452
  • 12
  • 53
  • 91
  • 1
    What is `Map`..? A class, an interface, an enum? – Sotirios Delimanolis Oct 25 '13 at 19:52
  • 4
    The built-in `Map` is an interface. Choose an implementing concrete class on the right side. – rgettman Oct 25 '13 at 19:53
  • 1
    Can you intantiate an interface ?? – Hussain Akhtar Wahid 'Ghouri' Oct 25 '13 at 19:57
  • 1
    To make it shorter, you can use the diamond operator `<>`. Java can infer the type arguments: `Map>> k = new HashMap<>();` And please use the interface instead the concrete type to declare your variable. This enables you, to alter the implementation at only one point of your source code. – Vertex Oct 25 '13 at 20:08
  • This object, by the way, is a map that uses a string as a key that points to a value that is a list of string and integer Pairs... I recommend writing it as a cohesive java object rather than a jumble of simple types. – Sandy Simonton Dec 04 '15 at 21:01

2 Answers2

78

The built-in Map is an interface, which cannot be instantiated. You can choose between lots of implementing concrete classes on the right side of your assignment, such as:

  • ConcurrentHashMap
  • HashMap
  • LinkedHashMap
  • TreeMap

and many others. The Javadocs for Map lists many direct concrete implementations.

rgettman
  • 176,041
  • 30
  • 275
  • 357
11

Interfaces cant be intantiated You need to use some concrete class implementing the interface Try something like this

Map<String, ArrayList<Pair<String, Integer>>> k = new  HashMap<String, ArrayList<Pair<String, Integer>>>();