2

I'm really new to these arraylist of hashmap. I want to create an arraylist of hashmap and will change the element of the arraylist in a loop dynamically. My code is as follows:

static List<HashMap<Character, Integer>> column = new ArrayList<HashMap<Character, Integer>>(9);
static HashMap<Character, Integer> columns = new HashMap<Character, Integer>();
for(int i=0;i<9;i++)//initialize?
    column.add(i, columns);
for(int i=0;i<9;i++) 
    column.get(i).put(b[xxx][xxx],(int)(b[xxx][xxx]));

At first I didn't use the for loop here, I thought I initialize the arraylist size in first line with (9) is enough, but when I tried to get element with column.get(5).put(something), it gave me exception with IndexOutOfBound.

Then I tried to use the column.add(i, null);, but it gave me the exception of NullPointerException. So I changed to this column.add(i, columns);

But now the problem is, when I tried to edit one of the hashmap in column arraylist, every other hashmap in the arraylist will be changed as well, I guess it's because they are set to be the same columns hashmap at first?

So my question is how to initialize the arraylist of hashmaps so that I can change every single one of them each time without affecting others?

1 Answer 1

6

You don't want to write

column.add(i, columns);

This keeps adding a reference to the same HashMap. column will then have 9 references to the same object, so when one changes, they all change.

Instead you want

column.add(i, new HashMap<Character, Integer>());

Then you add a new instance each time.

Sign up to request clarification or add additional context in comments.

1 Comment

@Zip Glad I could help. Also note that you don't need to pass the index i unless you are inserting at index i. If you are just adding to the end of a list you should write column.add(new HashMap<Character, Integer>());

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.