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.