0

What is wrong with this code. why i am not able to get the entryset outside of this if condition?

public class test{

public static void main(String args[]) {

    ArrayList <String>recordList = new ArrayList();
    int c = 1;
    HashMap<Integer, ArrayList> recordbatchof1000 = new HashMap<>();

    for (int i = 0; i < 10; i++) {

        recordList.add(String.valueOf(i));
        if (recordList.size() > 0) {
            recordbatchof1000.put(c, recordList);
            System.out.println("DEBUG:: The value of the map is  inside if condition::" + recordbatchof1000.entrySet());
            c++;
            recordList.clear();
        }
            System.out.println("DEBUG:: The value of the map is  outside if condition::" + recordbatchof1000.entrySet());
    }
    }

I am getting the output as shown below but I am expecting same output inside and outside of if condition... DEBUG:: The value of the map is inside if condition::[1=[0]]

DEBUG:: The value of the map is outside if condition::[1=[]]

DEBUG:: The value of the map is inside if condition::[1=[1], 2=[1]]

DEBUG:: The value of the map is outside if condition::[1=[], 2=[]]

I am trying to add records in hashmap and read it at once outside.

Shaheaz
  • 23
  • 5
  • You clear the list after adding it. [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) should be a good read to understand the problem. – Chaosfire May 31 '23 at 11:00
  • You only create one `ArrayList recordList` that you fill with data, add a reference to it to `recordbatchof1000` and then empty it again with `recordList.clear();`. After the `if` statement the `recordList` is always empty (and the references that you added to `recordbatchof1000` show that too). To fix this you **must** create new lists that you can add to `recordbatchof1000`. – Thomas Kläger May 31 '23 at 11:00

0 Answers0