1
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class A
{
    private Set<String> users = new HashSet<String>();

    public Set<String> getUsers()
    {
        return users;
    }

    public void setUsers( Set<String> users )
    {
        this.users.clear();
        if( users != null )
        {
            this.users.addAll( users );
        }
    }

    public static void main( String[] args )
    {
        A a = new A();
        Set<String> temp = new HashSet<String>();
        temp.add( "a1" );
        temp.add( "a2" );
        a.setUsers( temp );
        Set<String> previousUsers = a.getUsers();
        System.out.println( previousUsers.size() ); //output 2

        temp.add( "a3" );
        a.setUsers( temp );
        System.out.println( previousUsers.size() );//output 3, how to make it still 2?
    }
}

问题:如果我想previuosUsers在调用新的 setUsers 后仍然保留旧值,我应该如何修改这个程序?

4

4 回答 4

0

尝试:

public Set<String> getUsers()
{
    return (Set<String>)users.clone();
}

如果我希望 previuosUsers 在调用新 setUsers 后仍保留旧值。

这意味着在其中修改的集合setUsers不能与 所指向的集合相同previousUsers。因此,在getUsers返回集合的副本而不是对同一集合的引用。这就是克隆所做的。

于 2012-11-13T06:28:12.190 回答
0

您可以改用此构造函数public HashSet(Collection<? extends E> c),而不仅仅是直接将返回分配给previousUsers.

于 2012-11-13T06:30:01.580 回答
0
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class A
{
    private Set<String> users = new HashSet<String>(), prevUsers = new HashSet<String>();    
    public Set<String> getUsers()
    {
        return users;
    }

    public void setUsers( Set<String> users )
    {
        this.prevUsers = new HashSet<String>(users); // saves a copy of users in prevUsers
        this.users.clear();
        if( users != null )
        {
            this.users.addAll( users );
        }
    }
    public Set<String> getPrevUsers() { 
        return this.prevUsers; 

    }
    public static void main( String[] args )
    {
        Set<String> previousUsers = a.getPreviousUsers();
        System.out.println( previousUsers.size() ); //output 2

        temp.add( "a3" );
        a.setUsers( temp );
        System.out.println( a.getPreviousUsers.size() );//output 3, how to make it still 2?
    }
}
于 2012-11-13T06:32:54.653 回答
0

这是你期待的吗

 public Set<String> getUsers()
{
    Set<String> users1 =  new HashSet<String>();
    users1.addAll(users);
    return users1;
}

public void setUsers( Set<String> users )
{
    this.users = users;

}
于 2012-11-13T06:33:04.937 回答