Saurabh Mishra
Saurabh Mishra

Reputation: 433

Java: HashMap behaving in an unexpected manner

So I have this hashmap with key as String and holds values as an integer array.

HashMap<String, Integer[]> h = new HashMap<String, Integer[]>();
h.put("PID", new Integer[] {3, 5});

I was trying int first, but then I read somewhere that primitive types can't be used in generics.

So, Eclipse says

Multiple markers at this line
- Syntax error on token(s), misplaced construct(s)
- Syntax error on tokens, ConstructorHeaderName expected 
 instead
- Syntax error on tokens, delete these tokens

for the second line. First line is fine for it.

Upvotes: 0

Views: 1179

Answers (2)

java seeker
java seeker

Reputation: 1266

This statement must be executed inside of any function or constructor. you can not insert, delete or update in global space.

This is a statement, you can't write statement at the place you are trying to do

h.put("PID", new Integer[] {3, 5});

Again you can not execute below statement because int[] is a primitive array and Integer[] is a arary of Integer Object. you have declared key,value == String,Integer[] so you can not insert int[] array

h.put("PID", new int[] {3, 5});

Again java Hashmap does not support primitive data type. you must have to use Object as key or value of Hashamp.

Upvotes: 1

DMaguireKane
DMaguireKane

Reputation: 96

This code works fine for me:

import java.util.HashMap;

public class HelloWorld{

     public static void main(String []args){
        HashMap<String, int[]> h = new HashMap<String, int[]>();
        h.put("PID", new int[] {3, 5});


        System.out.println(h.get("PID")[0]); //prints "3"
        System.out.println(h.get("PID")[1]); //prints "5"
     }
}

Upvotes: 1

Related Questions