来自 c++ 世界,我发现阅读 HashSet 文档有些困难:
在 c++ 中,您将拥有:
这又指向:
这使得对 a 处理的元素类型的要求很明显std::set
。Set
我的问题是: Java 中a 维护的元素类型 (E) 有哪些要求?
这是一个我无法理解的简短示例:
import gdcm.Tag;
import java.util.Set;
import java.util.HashSet;
public class TestTag
{
public static void main(String[] args) throws Exception
{
Tag t1 = new Tag(0x8,0x8);
Tag t2 = new Tag(0x8,0x8);
if( t1 == t2 )
throw new Exception("Instances are identical" );
if( !t1.equals(t2) )
throw new Exception("Instances are different" );
if( t1.hashCode() != t2.hashCode() )
throw new Exception("hashCodes are different" );
Set<Tag> s = new HashSet<Tag>();
s.add(t1);
s.add(t2);
if( s.size() != 1 )
throw new Exception("Invalid size: " + s.size() );
}
}
上面的简单代码失败了:
Exception in thread "main" java.lang.Exception: Invalid size: 2 at TestTag.main(TestTag.java:42)
根据我对文档的阅读,只需要为 Set 实现 equals 运算符:
我从文档中遗漏了什么?