[英]Checking if value exists in ArrayList in a different class without creating a new list
[英]Checking if an instance of a specific class exists in a list
好的,如果已經回答了,請道歉。 我試着尋找,但我沒有找到答案。
現在,我有一個鏈表實用程序類(在一個方向上鏈接),其中包含用於不同事物的各種通用實用程序方法。 我想要做的是創建一個方法,該方法能夠將任何給定類的實例作為參數,然后繼續檢查列表中是否存在此類類的實例,如果存在則返回 true,如果存在則返回 false沒有。 該列表本身包含幾個不同類的實例。
該方法將與詳細說明游戲板上空間內容的列表結合使用:如果該空間包含敵人,則顯示敵人的圖標並使該空間不可通行,如果該空間包含項目,則顯示其圖標項目等等等等。 這里真正的關鍵是該方法應該能夠處理任何和所有類,所以我不能使用類似的東西:
if(foo instanceof Enemy) { . . . }
這是我最初嘗試做的://此方法位於 LinkedList 類中
public boolean exists(Object o)
{
int i = 0;
boolean output = false;
//koko() returns the size of the linked list
while(i < koko() && !output)
{
//alkio(i) returns an Object type reference to the entity in index i
if(alkio(i) instanceof o.getClass())
{
output = true;
}
}
return output;
}
但結果是: https : //www.dropbox.com/s/5mjr45uymxotzlq/Screenshot%202016-04-06%2001.16.59.png?dl=0
是的,這是作業(或者更確切地說,是大作業的一部分),但老師不會在凌晨兩點回答,而且我的 google-fu 太弱了。
哈哈
instanceof
的動態方法是使用Class.isInstance()
方法:
確定指定的
Object
是否與此Class
表示的對象賦值兼容。 此方法是 Java 語言instanceof
運算符的動態等效項。
所以, alkio(i) instanceof o.getClass()
應該寫成o.getClass().isInstance(alkio(i))
。
這個怎么樣?
public static void main(String[] args)
{
Integer myInt = 1;
System.out.println(exists(Arrays.asList(1, 2, 3), myInt)); //true
System.out.println(exists(Arrays.asList("1", "2", "3"), myInt)); //false
}
/**
* Returns whether an object exists in @list that is an instance of the class of object @o.
*/
public static boolean exists(List<?> list, Object o)
{
return list == null || o == null ? false : list.stream().filter(o.getClass()::isInstance).findAny().isPresent();
}
如果我正確理解您的問題,那么您需要將類傳遞給您的方法,而不是類的實例:
public boolean exists (Class checkClass) {
...
if (item.getClass().equals(checkClass)) {
return true;
}
...
}
然后您將其稱為:
if (myList.exists(Enemy.class)) {
...
}
但是,您應該考慮使用不同的模型,因為這顯示了一些相當糟糕的面向對象設計。 更好的方法是讓interface
代表可以在地圖上顯示的所有內容。 就像是:
public enum MapObjectType {
ENEMY, ALLY, WALL;
}
public interface MapObject {
MapObjectType getType();
}
然后,可以放入代表地圖的列表中的每個類都應實現此接口。 例如:
public class Enemy implements MapObject {
@Override
public MapObjectType getType() {
return MapObjectType.ENEMY;
}
}
那么你的方法可能更明智:
public boolean hasObjectOfType(MapObjectType type) {
...
if (item.getType().equals(type)) {
return true;
}
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.