2011-08-03 20 views
2

所以我有一個包含'screen'類型的自定義類對象的'Screens'列表,這些類是在運行時從XML文件中讀取的。在XML中還有一個名爲'path'的部分,它包含字符串,這些字符串被存儲爲'screen'對象的更多成員。我想要做的是在當前屏幕上讀取path.left的字符串值,並用它來設置currentScreen的新值。 即。 我知道.. currentScreen.path.left =「park」 所以我想.. currentScreen = currentChapter.Screens.park;使用字符串引用數組列表中的自定義類成員

但它不喜歡它..我嘗試了以下,但它不會在列表中找到它,因爲列表是'屏幕的,而不是字符串。謝謝。

String tmppath = currentScreen.path.left; 
int index = currentChapter.Screens.indexOf(tmppath); 
currentScreen = currentChapter.Screens.get(index); 

屏幕和路徑的對象是這樣的:

public class Screen { 
    public String id; 
    public Integer backdrop; 
    public Paths path; 
    public List<Integer> areaMode = new ArrayList<Integer>(); 
    public List<String> areaName = new ArrayList<String>(); 
    public List<Region> areaArray = new ArrayList<Region>(); 

    public Screen(String mid, Integer backDrop, Paths mpath, List<Integer> mareaMode ,List<String> mareaName, List<Region> mareaArray) { 
     id = mid; 
     backdrop = backDrop; 
     path = mpath; 
     areaMode = mareaMode; 
     areaName = mareaName; 
     areaArray = mareaArray; 
    } 
} 

public class Paths { 
    public String left; 
    public String right; 
    public String top; 
    public String bottom; 

    public Paths(String mleft, String mright, String mtop, String mbottom) { 
     left = mleft; 
     right = mright; 
     top = mtop; 
     bottom = mbottom; 
    } 
} 

我想我有另一個問題是,我試圖找到使用「身份證」串「屏幕」的實例我在裏面創建了它。

回答

2

indexOf()在您的對象上使用equals()操作來確定對象在列表中的位置。

所以,在你屏幕對象時,的equals()方法應使用路徑變量或它的某些部分的這個工作。不看這個對象就很難說。

@ Be77amy - 我在此做一個瘋狂的假設,即路徑變量等同於Screen對象的id。如果這是真的,那麼你的問題就大大簡化了。你應該實現像這樣的hashCode()和equals()方法 -

@Override 
public int hashCode() { 
    final int prime = 31; 
    int result = 1; 
    result = prime * result + ((id == null) ? 0 : id.hashCode()); 
    return result; 
} 

@Override 
public boolean equals(Object obj) { 
    if (this == obj) 
     return true; 
    if (obj == null) 
     return false; 
    if (getClass() != obj.getClass()) 
     return false; 
    Screen other = (Screen) obj; 
    if (id == null) { 
     if (other.id != null) 
      return false; 
    } else if (!id.equals(other.id)) 
     return false; 
    return true; 
} 

這也可以讓你通過id查找。

+0

將屏幕對象添加到原始文章 – Be77amy

+0

能夠適應此工作感謝 – Be77amy

+0

我建議謹慎實施基於對象數據的子集的等值語義(除非其餘數據是瞬態的或您的數據正在檢查是一個強制唯一的ID)。它可以讓你解決當前的問題,但是你可能最終會遇到很多令人頭痛的問題,其中一些其他數據結構等同於兩個不相同的屏幕。 –

2

嘗試使用地圖而不是列表。地圖允許您存儲鍵值對,因此您可以使用字符串鍵和您的自定義對象作爲值。

+0

問題在於,path.left/right/up/down是下一個屏幕的引用,路徑在屏幕內。我不是如何將這些對象與字符串鍵一起添加到地圖中,因爲它們都是在運行時從xml中讀取的 – Be77amy

+0

因此您從XML讀取屏幕對象。在該對象內部是一個Paths對象,您可以從中建立一個描述路徑的字符串。建立該字符串,然後做map.put(stringPath,screen) –

相關問題