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?
}
}
问题:如果我希望在调用新的setUsers之后previuosUsers
仍保留旧值,我应该如何修改此程序?
答案 0 :(得分:0)
尝试:
public Set<String> getUsers()
{
return (Set<String>)users.clone();
}
如果我想previuosUsers在调用新的setUser后仍保留旧值。
这意味着setUsers
内修改的集合不得与previousUsers
指向的集合相同。因此,在getUsers
内返回集合的副本,而不是对同一集合的引用。这就是clone的作用。
答案 1 :(得分:0)
您可以使用此构造函数代替public HashSet(Collection<? extends E> c)
,而不是直接将回报分配给previousUsers
。
答案 2 :(得分: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?
}
}
答案 3 :(得分: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;
}