4

Here I have two hashmaps dataz and screen_dataz. I want to copy screen_dataz to dataz.

I am trying like this but it's not working:

Object[]  obj = new Object[5];
String[] strArray = new String[]{"Obj1","Array1","Converted1","To1","List1"};
String[] strArray1 = new String[]{"Obj2","Array2","Converted2","To2","List2"};
dataz.put(0,(Object[]) strArray);
dataz.put(1,(Object[]) strArray1);
// String dataString = (String) dataz;
System.out.println(dataz);


Object[]  obj1= new Object[5];
String[] strArray2 = new String[]{"Obj3","Array3","Converted3","To3","List3"};
String[] strArray3 = new String[]{"Obj4","Array4","Converted4","To4","List4"};
screen_dataz.put(0,(Object[]) strArray2);
screen_dataz.put(1,(Object[]) strArray3);
System.out.println("copying screen dataz to dataz");
dataz.putAll(screen_dataz);
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
user
  • 101
  • 1
  • 1
  • 4

7 Answers7

17

Make use of constructor and Shallow it .

dataz = new HashMap<Key,val>(screen_dataz);
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • This *might* be a solution. But perhaps `dataz` already has some useful data in it. Probably worth waiting until the OP defines the question more closely. – Duncan Jones Jun 27 '13 at 07:48
  • 1
    hey, do `screen_dataz` and `dataz` refer to the same location? As I tried this and deleting values in `dataz` also deleted values from `screen_dataz`. I actually want to copy values from one map to a new map and not two variables referring to the same location. – Ram Patra Apr 09 '15 at 14:56
8

You can simply construct a new one:

dataz = new HashMap<Integer,Object>(screen_dataz);
Maroun
  • 94,125
  • 30
  • 188
  • 241
6
Map tmp = new HashMap(patch);
tmp.keySet().removeAll(target.keySet());
target.putAll(tmp);

For detailed explanation

Community
  • 1
  • 1
Naveen Kumar Alone
  • 7,536
  • 5
  • 36
  • 57
3

It's already posted here

Map tmp = new HashMap(patch);
tmp.keySet().removeAll(target.keySet());
target.putAll(tmp);
Community
  • 1
  • 1
u.jegan
  • 833
  • 6
  • 15
2

Looks like it's not working because you're using the same keys (0 and 1) both in dataz and in screen_dataz.

According to the official javadoc, putAll "will replace any mappings that this map had for any of the keys currently in the specified map.", so you are now losing your previous objects contained in dataz.

Raibaz
  • 9,280
  • 10
  • 44
  • 65
1

Try this

    HashMap<Integer,String> myMap=new HashMap<>();
    myMap.put(1,"A");
    myMap.put(2,"B");
    HashMap<Integer,String> newMap=new HashMap<>();
    newMap.putAll(myMap);
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0
HashMap<String, String> hash1 = new HashMap();
    hash1.put("one", "the firs one");
    hash1.put("two", "the second one");
    hash1.put("three", "the third one");
    HashMap<String, String> hash2 = new HashMap<>();
    hash2.putAll(hash1);
Mostafa Jamareh
  • 1,389
  • 4
  • 22
  • 54