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.

Recommended Answers

All 3 Replies

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.

commented: ton of thanks...dear taywin..this is perfectly worked.... +1

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.