There are multiple ways of going about this. First, you could do a simple for loop, iterating over all of the objects until one with a specific id is found. Your search complexity would be O(N)
anObject obj = null;
dance: for( int i = 0; i < objects.length; i++ )
{
if( object[i].id == 2 )
{
obj = object[i];
break dance;
}
}
if you know that you're always going to be searching by id, you could implement Comparable. Then you can use java.util.Arrays to sort and search the array for you. This reduces your search to O(log n)
public class anObject implements Comparable {
public String id, otherProperty;
public anObject(){
this.id = "1";
this.otherProperty = "cat";
}
public int compareTo( Object o )
{
if( o instanceof anObject )
{
return this.id.compareTo( ( (anObject) other).id );
}
return -1;
}
}
Last option, you can store the results in a Map<String, anObject>. If you're doing a lot of searching, this is the best method as it gives your search O(1), at the cost of additional memory.