Java·JVM

Collection의 생성자로 Collection을 넣으면 어떻게 될까?

Collection의 생성자로 Collection을 넣으면 어떻게 될까? 대표 이미지
package testSet;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Set;

public class SetTester {

public static void main(String[] args) {
// TODO Auto-generated method stub
Hashtable<String,String> hashtable = new Hashtable<String, String>();
hashtable.put("key1","value1");
hashtable.put("key2", "value2");
hashtable.put("key3", "value3");

System.out.println("key1 = "+hashtable.get("key1"));
System.out.println("key2 = "+hashtable.get("key2"));
System.out.println("key3 = "+hashtable.get("key3"));


Hashtable<String,String> hashtable2 = new Hashtable<String,String>(hashtable);
Set hashSet1 = hashtable2.keySet();
Object[] array = hashSet1.toArray();

HashSet hashSet = new HashSet(hashSet1);
System.out.println(hashSet.toString());

hashSet.remove("key3");

System.out.println("remove key3 from hashSet"+hashSet.toString());


System.out.println(hashSet1.toString());
System.out.println(array.length);
hashSet1.remove("key1");

System.out.println(hashSet1.toString());

System.out.println(array.length);

System.out.println("key1 = "+hashtable.get("key1"));
System.out.println("key2 = "+hashtable.get("key2"));
System.out.println("key3 = "+hashtable.get("key3"));


System.out.println("key1 = "+hashtable2.get("key1"));
System.out.println("key2 = "+hashtable2.get("key2"));
System.out.println("key3 = "+hashtable2.get("key3"));

System.out.println(array[2]+" = "+hashtable2.get(array[2]));
System.out.println(array[1]+" = "+hashtable2.get(array[1]));
System.out.println(array[0]+" = "+hashtable2.get(array[0]));

//결론 Collection의 생성자에 Collection을 매게변수로 넘겨주면 새로 생기는 Collection이 매개변수 Collection의 모든 데이터들을 복제해서 저장한다.
//같은 데이터에대한 중복된 참조가 전혀 없다는 뜻이다.

}

}

댓글