2016-08-19 45 views
-1

我喜歡這個在android系統的arrray Arrays.asList的使用是不同的,因爲我做了不同的類「人」的陣列從一個數組得到一個元素的索引:如何使用Arrays.asList

people = new Person[]{ 
      new Person("Python"), 
      new Person("PHP"), 
      new Person("Pascol"), 
      new Person("PyCrust"), 
      new Person("C"), 
      new Person("C#"), 
      new Person("C++") 

    }; 

,我用Arrays.asList這樣

int index= Arrays.asList(people).indexOf("Pascol"); 
    String tags = Integer.toString(index); 
    Toast.makeText(getApplication(),tags,Toast.LENGTH_SHORT).show(); 

,但我得到的值「-1」的祝酒辭。 我無法找到故障。

+0

INT指數= Arrays.asList(人).indexOf(新的人( 「Pascol」)); –

+0

您需要重寫Person類中的equals()和hashcode(),並使用「pascol」而不是僅字符串發送Person對象。 – kosa

+0

[indexOf()可能重複將找不到自定義對象類型](http://stackoverflow.com/questions/24957813/indexof-will-not-find-a-custom-object-type) – kosa

回答

1

問題是你有一個Person對象的列表。當您致電.indexOf("Pascol");時,您通過String。比較有String一個Person將返回始終false.Do這個代替

int index = -1; 
for (int i = 0; i < people.length; i++) { 
    if (people[i].getName().equals("Pascol")) { 
     index = i; 
    } 
} 

String tags = Integer.toString(index); 
    Toast.makeText(getApplication(),tags,Toast.LENGTH_SHORT).show(); 
0

你應該實現可比<>在Person類

1
int index = Arrays.asList(people).indexOf("Pascol"); 

PascolString在這裏,但你的數組中的對象是Person類型對象。因此indexOf方法不能與StringPerson匹配。您需要覆蓋equals()hashcode()並將Person類型參數傳遞給indexOf,其名稱爲Pascol。當然,我認爲你的對象的平等只取決於名稱屬性。