William Willi William Willi - 3 months ago 10
Android Question

How to get the Index of an element from an array using Arrays.asList

I got an arrray like this in android the usage of Arrays.asList is different because i made the Array with different class "Person":

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

};


and i used Arrays.asList in this way

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


But i get the value "-1"in the toast.
i could not find the fault.

Answer

The problem is that you have a list of Person objects. When you call .indexOf("Pascol"); you pass in a String. Comparing a Person with a String will return always false.Do this instead

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();