简体   繁体   English

检查泛型类型的对象是否在LinkedList中

[英]Check if an object of generic type is in LinkedList

I have a LinkedList of generic type State . 我有一个通用类型StateLinkedList In this LinkedList I have hundreds or even thousands of State objects. 在此LinkedList我有数百甚至数千个State对象。 How can I, in the most efficient way to check if newly generated State object is already in the list? 如何以最有效的方式检查列表中是否已包含新生成的State对象?

State object: 状态对象:

public State(PlayerAddress player, LinkedList<BoxAddress> boxList, char[][] map, String solution, String stateHash) {
    this.player = player;
    this.boxList = boxList;
    this.map = map;
    this.solution = solution;
    this.stateHash = stateHash;
    boxListString = boxListToString(boxList);
    mapString = mapString(map);
}
}

Additionally, State object consists of another generic objects as it is shown in the Constructor. 此外,状态对象由构造函数中所示的另一个通用对象组成。 How can I check if both State objects are the same in every aspect (PlayerAddress, LinkedList, etc.) ? 如何检查两个State对象在各个方面(PlayerAddress,LinkedList等)是否相同?

Have you tried the contains method? 您是否尝试过contains方法? This could work. 这可能有效。 Also don't forget that you can overwrite stuff, so you could compare the hascodes as well by overwriting the hascode and compare methods. 同样不要忘记,您可以覆盖内容,因此您也可以通过覆盖hascode和compare方法来比较hascodes。

In your case I would strongly suggest you will utilize the contains method. 在您的情况下,我强烈建议您使用contains方法。 Which is the most efficient lookup for your case. 这是最适合您的情况的查询。

Looking at the java doc for contains: 在Java文档中查找包含:

public boolean contains(Object o) Returns true if this list contains the specified element. public boolean contains(Object o)如果此列表包含指定的元素,则返回true。 More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)). 更正式地讲,当且仅当此列表包含至少一个元素(e == null?e == null:o.equals(e))时,返回true。

So you should only need to overwrite equals for your State class. 因此,您只需要覆盖State类的equals。 The hashcode, will be required for sets. 集需要哈希码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM