0

Let's say I have a map and a List. How can i put more lists for different keys? I know that the list is transmitted through a reference, but what's the way to do it, closest to this one?

    Map<Integer, List<Integer>> moves = new HashMap<Integer,List<Integer>>();
    List<Integer> values = new LinkedList<Integer>();

    //Populate the map of moves to use it later for equation verification
    values.add(6);values.add(9);
    moves.put(0, values);
    values.clear();
    moves.put(1, values);
    values.add(3);
    moves.put(2,values);
    values.clear();
    values.add(2);values.add(5);
    moves.put(3, values);
    values.clear();
    moves.put(4, values);
    values.add(3);
    moves.put(5,values);
    values.clear();
    values.add(0);values.add(9);
    moves.put(6,values);
    values.clear();
    moves.put(7, values);
    moves.put(8, values);
    values.add(0);values.add(6);
    moves.put(9, values);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Turbut Alin
  • 2,568
  • 1
  • 21
  • 30
  • 1
    @AndrewThompson i don't understand xD what you mean – nachokk Dec 15 '13 at 21:00
  • @nachokk It was only when I read what I wrote, prompted by you, that I thought *"What the heck did I write that for? What a complete load of nonsense!"* (And by nonsense I do mean nonsensical, rather than just incorrect.) Apologies to all, for the noise. – Andrew Thompson Dec 15 '13 at 21:04

2 Answers2

2

You create new instances of the ArrayList, containing your values.

moves.put(0, new ArrayList<Integer>( values ));

That way you won't need to associate the values reference to a new object each time.

Georgian
  • 8,795
  • 8
  • 46
  • 87
  • @TurbutAlin I suggest you used `ArrayList` instead of `LinkedList`, by the way. I wrote `ArrayList` from reflex. – Georgian Dec 15 '13 at 21:02
  • Why use the ArrayList instead of LinkedList? Because of the memory used by LinkedList? – Turbut Alin Dec 15 '13 at 21:06
  • @TurbutAlin For your needs, it is best you got used to the `ArrayList` implementation of `List`. Also, in 95% of the cases, the `ArrayList` is used. But if you're really keen on learning the details, a quick Google Search will do. :-) Best of luck. – Georgian Dec 15 '13 at 21:11
  • @TurbutAlin you can read more [here](http://stackoverflow.com/a/322742/2415194) but im not sure why to use arrayList rather than linkedlist in this context.. – nachokk Dec 15 '13 at 21:15
1

You have to create a new object. If not you are putting the same instance in all keys and all keys would have the same instance when you retrieve its value from map.

Map<Integer, List<Integer>> moves = new HashMap<Integer,List<Integer>>();
List<Integer> values = new LinkedList<Integer>();

//Populate the map of moves to use it later for equation verification
values.add(6);values.add(9);
moves.put(0, values);
values = new LinkedList<Integer>();
values.add(8);
moves.put(1, values);
nachokk
  • 14,363
  • 4
  • 24
  • 53