I would like to know the conditions under which ArrayList will be modified due to future data.

Asked 2 years ago, Updated 2 years ago, 94 views

I thought ArrayList only registers data in order.

When HashMap with the same key value was registered consecutively, the data registered first were changed to the same data as the last registered data.

As a result of testing this and that, I think it only happens when the key value is the same, but does ArrayList modify the previously registered data if the data with the same key value comes in?

Or do you need other conditions?

The code was roughly like this at that time.

    ArrayList<HashMap<String, String>> al = new ArrayList<HashMap<String, String>>();
    HashMap<String, String> hm = new HashMap<String, String>();

    for (int i=0; i<3 ; i++ )
    { 
        hm.put ("list", i);
        aList.add(hm);
        System.out.println("aList >>> : " + aList);
    }

For your information, I know that you can transfer HashMap = new HashMap(); in the for statement.

What I want to know is that the data registered in the ArrayList is modified due to the data registered later.

arraylist

2022-09-20 19:44

1 Answers

Well, if you write with the body, you create one hashmap object and save only the same reference three times.

It's easy to understand if you have the concept of a pointer in c/c++. The only way to create on a heap in Java is to use the new operator.

HashMap<String, String> hm = new HashMap<String, String>(); created the object and the hm variable points to it.

aList.add(hm); to list is a reference that points to an object, not an object. So you put the same object three times.

So how do you put each different object three times?

You can create each object with the number 3 new operator in the for and register it on the list as shown below.

ArrayList<HashMap<String, String>> al = new ArrayList<HashMap<String, String>>();
HashMap<String, String> hm = null;

    for (int i=0; i<3 ; i++ )
    { 
        hm = new HashMap<String, String>();
        hm.put ("list", i);
        aList.add(hm);
        System.out.println("aList >>> : " + aList);
    }


2022-09-20 19:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.