2013-05-29 74 views
3

我试图从类与格式列表中提取独特的元素:麻烦唯一列表元素

[EntityClientPlayerMP['Player989'/228, l='MpServer', x=138.16, y=68.62, z=522.96], EntityCow['Cow'/231, l='MpServer', x=143.63, y=68.00, z=527.50]....] 

这些列表的尺寸通常为60-100。

我想在目前所使用的方法是

List<Class> uniqueList = new ArrayList<Class>(new HashSet<Class>(fullList)); 

这将返回完全相同的名单,但排序略有不同。任何想法为什么?

+0

你是什么意思“排序有点不同”?你能提供一个例子吗? – chessbot

+0

你的'Class'类是什么样的? (我假设你不是指'java.lang.Class'?) – ruakh

+0

这听起来很像“_I没有实现hashCode()和equals()_”的问题。 – jahroy

回答

2

你需要为equals()hashcode()提供正确实施

2

不要忘了覆盖每个实体类(why?)的equals()hashCode()方法,否则设置将无法正确判断当两个元素相等时。另外,我觉得你的意思是这样的:

List<EntityClientPlayerMP> uniqueList = 
    new ArrayList<EntityClientPlayerMP>(
     new LinkedHashSet<EntityClientPlayerMP>(fullList)); 

现在在上面的代码片段类型参数是一个在特定的(如问题出不Class,并根据需要的实际类型替换),并通过使用LinkedHashSet我们保证保留原始列表中的排序。

+0

示例列表不仅包含“EntityClientPlayerMP”,还包含“EntityCow”。推测这些是OP的“Class”类型的子类型。 – Arend

+0

@Arend在这种情况下,你会想要对象。 – user949300

+0

我的意思是,显然OP已经定义了他自己的类型'Class',其中'EntityClientPlayerMP'和'EntityCow'是子类型。当然,这只是闲散的猜测,并且与问题几乎没有关系(对于我没有什么补充的答案)。 – Arend

3

它们的排列方式不同,因为HashSet具有“怪异”排序,基于对象的hashCode。要保留订购,请使用LinkedHashSet

至于唯一性,设置将使用equals()hashCode(),所以请确保这些都正确实施。有时可以使用的懒惰技巧是使用对象的toString()方法(并在字符串上调用hashCode和equals)。