sldroid sldroid - 6 months ago 29
Java Question

How to get position of element in ArrayList

I used following method to add my data to ArrayList.

ArrayList<Word> wordList = new ArrayList<Word>();
Word word = new Word();

After the add some data, I want find the position of the any id which I want find in ArrayList.

Already I have tried following method to get position by id. But it isn't work.

int position = wordList.indexOf(id);


int position = wordList.lastIndexOf(id);

Both codes always generated "position = -1" as a result. How can I do that?


This is the code of the class. How can I implement equal method?

public class Word {
private String _id, word, definition, favourite, usage;

public String get_id() {
return _id;

public void set_id(String _id) {
this._id = _id;

public String getWord() {
return word;

public void setWord(String word) {
this.word = word;

public String getDefinition() {
return definition;

public void setDefinition(String definition) {
this.definition = definition;

public String getFavourite() {
return favourite;

public void setFavourite(String favourite) {
this.favourite = favourite;

public String getUsage() {
return usage;

public void setUsage(String usage) {
this.usage = usage;


indexOf is trying to compare Word objects. Your list doesn't contain ids as the elements, so you get -1.

You need to use a loop and search the list.

int id = 3; 
int position = -1;
for (int i = 0; i < wordlist.size(); i++) {
    if (wordlist.get(i).getId() == id) position = i;

Note: this will search the whole list to find the last index of that id. So if there are duplicates and you only want the first one (or stop the loop as soon as you find what you want) add a break in the if statement.