0

dear all,
I am working on hashmap and treemap.
At the starting of my program i have declared two map,m1 and temp,both are hashmap.

At starting point both map contains same kay value pair.

At some instance of program, i want to change the value in temp, remove some key value pair and after some processing i want to again get original value of remaining key from m1.

So my problem is when i am copying value frm m1, instead of value address of that value is cpoied,so later my m1 map doesn't contain original value.

here i am showing some code of that.

public static Map<Integer,String[]> m1 = new TreeMap<Integer,String[]>();
public static Map<Integer,String[]> temp = new TreeMap<Integer,String[]>();

for(Map.Entry<Integer, String[]> mapEntry2 : temp.entrySet())
        {
        int key3 = mapEntry2.getKey();
        //String[] dd = mapEntry2.getValue();
        System.out.print("\nvalue of key3 = "+key3);
        if(m1.containsKey(key3))
        {
        String[] aa5=m1.get(key3);
        //mapEntry2.setValue(aa5);
        temp.put(key3,aa5);
        }
    }

So i got problem at temp.put() method,instead of putting value, it put address of value in m1.So next time i modify value in temp,this modification is also reflected in m1.

please tell me what to do? for inserting value instead of address.

2
Contributors
3
Replies
4
Views
4 Years
Discussion Span
Last Post by jalpesh_007
1

You simply copy the value of the aa5 to another new array before you put it in the temp.

String[] aa5 = m1.get(key3);
String[] newAA = new String[aa5.length];  // create a new array with the same length
for(int i=0; i<aa5.length; i++) { newAA[i] = aa5[i]; }  // copy each value
temp.put(key3, newAA);  // now you have a new array to be stored

You could use this type of copying with any type of array data type when you do not want to have a deep copy.

Votes + Comments
ton of thanks...dear taywin..this is perfectly worked....
0

thanks...its work correctly...i am facing this problem since last two weeks...now my work go further....again thanks...

0

thanks...its work correctly...i am facing this problem since last two weeks...now my work go further....again thanks...

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.