
Untitled
By: a guest on
Aug 12th, 2012 | syntax:
None | size: 1.46 KB | hits: 7 | expires: Never
package zwei;
import java.util.HashMap;
public class bla {
//Shallow copy
static HashMap<Integer, String> kopie = new HashMap<Integer, String>();
//deep Copy
static HashMap<Integer, String> kopie2 = new HashMap<Integer, String>();
//ursprüngliche map zum verändern
static HashMap<Integer, String> zwo = new HashMap<Integer, String>();
//Shallow copy constructor
public bla(HashMap<Integer, String> zwo){
kopie = zwo;
}
//Deep copy constructor (int i ist nur zum aufrufen wichtig!)
public bla(int i, HashMap<Integer, String> zwo){
for(Integer single : zwo.keySet()){
kopie2.put(single, zwo.get(single));
}
}
public static void main(String[] args) {
//Map wird mir inhalt gefüllt
for(int i=0 ; i<10 ; i++){
zwo.put(i, "wurstkopf"+i);
}
//Shallo copy wird erzeugt
bla abc = new bla(zwo);
//Deep copy wird erzeugt
bla def = new bla(1, zwo);
//Ursprüngliche map wird verändert um shallo copy zu beweisen
zwo.remove(2);
zwo.put(2, "Neeee");
zwo.remove(6);
zwo.put(6, "BÄM");
//ausgabe kopie (veränderungen müssen auftauchen)
for(Integer single : kopie.keySet()){
System.out.println(single);
System.out.println(kopie.get(single));
}
System.out.println("-----------");
//ausgabe kopie (ohne veränderungen!)
for(Integer single : kopie2.keySet()){
System.out.println(single);
System.out.println(kopie2.get(single));
}
}
}