1

I have the following HashMap:-

HashMap<Integer,Integer[]> possibleSeq = new HashMap<Integer,Integer[] >();

I would like to add into the map something like this:-

 possibleSeq.put(1,{1,2,3,4});

There are a large number of entries and i am supposed to enter manually:- I tried doing this:-

Integer a = 1;
Integer aArr = {1,2,3,4};
  possibleSeq.put(a,aArr);

But this is not my requirement.I dont want to create separate Integer variables to store keys and separate Integer Arrays to store my values ie IntegerArray .Any Ideas??

3
  • Why Integer[]? I'm pretty sure you need int[]. Commented Jul 30, 2013 at 14:41
  • Generics don't work on primitives I think Commented Jul 30, 2013 at 14:58
  • int[] is an array, which is an object, so it's OK. Just tried it, works fine. Commented Jul 30, 2013 at 15:00

4 Answers 4

7

How about this:

public static void put(Map<Integer, Integer[]> map, Integer k, Integer... v) {
    map.put(k, v);
}

...

put(map, 1, 1,2,3,4);
Sign up to request clarification or add additional context in comments.

3 Comments

+1, I like this, quite neat. You could even extend Map to create a more "native" looking api.
And you can go further with a builder that has map as a field and can return this for chaining.
And while on the subject of builders, by all means provide a factory method with a short name, which you can import static. That brings conciseness to the peak, without hurting readability a bit.
1

You can new the Integer[] inline:

possibleSeq.put(1, new Integer[]{1,2,3,4});

1 Comment

Oh Yes!! ...My bad!! ...+1 for the answer:)
0
possibleSeq.put(1,{1,2,3,4});

This is not valid Java syntax. Try this instead:

possibleSeq.put(1, new Integer[]{1,2,3,4});

Comments

0

{1,2,3,4,5,6} is not an array new Integer[]{1,2,3,4,5} is an array of integers.

 possibleSeq.put(1,new Integer[]{1,2,3,4});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.