集合对象-“块数据”操作--其实是同一对象引用

例如:

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 );

set2 与 set3 中存储的都是 set1 元素的 “引用”


代码如下:

/**
 * 测试 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( "\n" );
	}
	
	/**
	 * 测试元素为应用类型
	 */
	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)

你可能感兴趣的:(String,object,测试,null,Collections,Integer)