Clear an Object already inserted to a hashmap

calls is an arrayList, customerCalls is a hashMap. I was debugging using eclipse and I fount that calls.clear clear the arrayList object already inserted in the customerCalls Hashmap. I am confused because I thought that once the object was submitted to another data structure, it has an independent entity and no operations can be taken on it unless I access this data structure containing it.

I need to clear the arrayList calls to make it free for a new set of calls that would be dedicated to another contract and later inserted as value for the hashmap key (contract Number). Not clearing it accumlates all calls as it appends current iteration addition to the past iteration one.

>     if (callContractID.equals(currentContractID)==false){
>                               customerCalls.put(currentContractID, calls);
>                               currentContractID =  callContractID;
>                               calls.clear();
>                               calls.add(call);
>                               count++;
>     }
     else {

        calls.add(call);
         }
Jon Skeet
people
quotationmark

I am confused because I thought that once the object was submitted to another data structure, it has an independent entity and no operations can be taken on it unless I access this data structure containing it.

No. The map contains a reference to an object... just as if you simply assigned another variable to it. You can have lots of references to the same object, and any changes made via one reference will be seen via any of the others. As a very simple example:

StringBuilder b1 = new StringBuilder();
StringBuilder b2 = b1;
b2.append("foo");
System.out.println(b1); // Prints foo

The exact same thing happens with collections:

StringBuilder b1 = new StringBuilder();
List<StringBuilder> list = new List<StringBuilder>();
list.add(b1);

StringBuilder b2 = list.get(0);
// Now b1 and b2 are both reference to the same object...
b2.append("foo");
System.out.println(b1); // Prints foo

people

See more on this question at Stackoverflow