LinkedHashSet的 java 文档说明了这一点:
请注意,如果将元素重新插入集合中,则插入顺序不受影响。(如果 s.add(e) 被调用,而 s.contains(e) 将在调用之前立即返回 true,则元素 e 被重新插入到集合 s 中。)
对于最近的一个项目,我决定使用一个在客户端-服务器通信中保存一组数据令牌,以便在某些列表视图小部件中显示给用户。我的想法是我可以用更新的数据廉价地重新插入元素,并且用户不会感到惊讶,因为顺序不会改变。
显然情况并非如此,使用 Oracle JRE 1.7.0_55-b13 它像任何其他Set一样运行,正如这个简短的测试程序所示:
import java.util.LinkedHashSet;
import static java.util.Arrays.deepToString;
public class LhsStack
{
public static class T
{
public T ( int id ) { this.id = id; }
public final Integer id;
public String value;
@Override
public int hashCode () { return id.hashCode (); }
@Override
public boolean equals ( Object obj )
{
return obj instanceof T && id.equals ( ((T)obj).id );
}
@Override
public String toString () { return id + " => " + value; }
}
public static void main ( String [] args )
{
LinkedHashSet < T > set = new LinkedHashSet <> ();
T a = new T ( 1 ),
b = new T ( 1 ),
c = new T ( 2 ),
d = new T ( 3 );
a.value = "Hello, World";
b.value = "World, Hello";
c.value = "Foo";
d.value = "Bar";
System.out.println ( "a == b: " + a.equals ( b ) );
if ( set.add ( a ) ) {
System.out.println ( "Inserted: " + a.value );
}
System.out.println ( "set.contains ( a ): " + set.contains ( a ) );
System.out.println ( "set.contains ( b ): " + set.contains ( b ) );
set.add ( c ); set.add ( d );
System.out.println ( "Elements: " + set.size () );
System.out.println ( deepToString ( set.toArray () ) );
if ( set.add ( b ) ) {
System.out.println ( "Re-Inserted: " + b.value );
}
else
{
System.out.println ( "Removing and Adding: " + b.value );
set.remove ( b );
set.add ( b );
}
System.out.println ( "Elements: " + set.size () );
System.out.println ( deepToString ( set.toArray () ) );
}
}
输出
a == b: true
Inserted: Hello, World
set.contains ( a ): true
set.contains ( b ): true
Elements: 3
[1 => Hello, World, 2 => Foo, 3 => Bar]
Removing and Adding: World, Hello
Elements: 3
[2 => Foo, 3 => Bar, 1 => World, Hello]
因此,我的问题是,由于元素b没有重新插入到集合中(即必须将其删除,然后重新添加以更新其值),那么 java 文档中注释的意义是什么?
谢谢!