集合オブジェクト-「ブロック・データ」アクション--実は同じオブジェクト参照
例:
Set set1 = new HashSet();
set1.add( object1 );
set1.add( ... );
set1.add( objectn );
Set set2 = new HashSet( set1 );
または
Set set3 = new HashSet( set1 );
set3.addAll( set1 );
set 2とset 3に格納されているのはset 1要素の「参照」です.
コードは次のとおりです.
set1 (b, 25) (c, 26) (a, 20) set2 (a, 20) (b, 25) (c, 26) set1 after modify element Person {name a->abc }: (b, 25) (c, 26) (abc, 20) set2 after set1 modify element: (abc, 20) (b, 25) (c, 26)
Set set1 = new HashSet();
set1.add( object1 );
set1.add( ... );
set1.add( objectn );
Set set2 = new HashSet( set1 );
または
Set set3 = new HashSet( set1 );
set3.addAll( set1 );
set 2とset 3に格納されているのはset 1要素の「参照」です.
コードは次のとおりです.
/**
* addAll( Collections )
* 。
* @author gqltt
*
*/
public class SetAddAllTest {
/**
* @param args
*/
public static void main(String[] args) {
testSetWithPerson();
}
private static <T> void print( String desc, Set<T> set ){
System.out.println( desc );
for( T s : set ){
System.out.print( s + " ");
}
System.out.println( "
" );
}
/**
*
*/
private static void testSetWithPerson(){
Set<Person> set1 = new HashSet<Person>();
set1.add( new Person("b", 25) );
set1.add( new Person("a", 20) );
set1.add( new Person("c", 26) );
Set<Person> set2 = new TreeSet<Person>();
set2.addAll( set1 );
//
print( "set1", set1 );
print( "set2", set2 );
changeName( getPersonByName( set1, "a" ), "abc" );
print( "set1 after modify element Person {name a->abc }:", set1 );
print( "set2 after set1 modify element:", set2 );
}
private static Person getPersonByName( Set<Person> set, String name ){
for( Person p : set ){
if( p.name.equals( name ) ){
return p;
}
}
return null;
}
private static void changeName( Person p, String newName ){
p.setName( newName );
}
static class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "(" + name + ", " + age + ")";
}
@Override
public int compareTo(Person person) {
return age - person.age;
}
@Override
public boolean equals(Object obj) {
if( obj == null ){
return false;
}
if( ! ( getClass() == obj.getClass() ) ){
return false;
}
Person p = (Person) obj;
return name != null && name.equals( p.name ) && age == p.age;
}
@Override
public int hashCode() {
int result = 47;
result += name.hashCode();
result += new Integer( age ).hashCode();
return result;
}
}
}
テスト結果出力:set1 (b, 25) (c, 26) (a, 20) set2 (a, 20) (b, 25) (c, 26) set1 after modify element Person {name a->abc }: (b, 25) (c, 26) (abc, 20) set2 after set1 modify element: (abc, 20) (b, 25) (c, 26)