Find an Object in an ArrayList with Java

Let’s say you have an ArrayList in Java.

ArrayList<String> a = new ArrayList<String>();
a.add("abc");
a.add("def");
a.add("ghi");

Now let’s say you wanted to grab the “def” object out of it. You could do this in the following way:

String b = a.get(a.indexOf("def"));

You can only retrieve an object from an ArrayList by its index. So a simple workaround is first to find the index of the object and then grab the object using that index.

This is a very trivial example, but this type of thing can be handy at times.

Note: If you are using a class like String from the Java framework that has an explicit equals method built into it, this will be easy. However, if the ArrayList contains objects of a custom class, you will likely need to override the equals and hashCode methods.

2 Responses to “Find an Object in an ArrayList with Java”

  1. what if i wanted to search for flights?
    lets say if we have an arraylist of flights
    and the flight is like flight(flightno, departing place …)
    how are we going to search for the flight number and return the array ?

  2. Hi Ming,

    Have you seen this post: http://code.hammerpig.com/how-to-compare-two-objects-in-java-by-overriding-equals.html

    Please let me know if it doesn’t answer your question.

Leave a Reply