Is there a better way than just iterating over and manually comparing two fields for each object, and then breaking when they are detected? It just seems so dirty looking for the best way.
If your problem is maintainability, you can do something with Fabian Steeg (what I would do), although this is probably not the “most efficient” (because you need to sort the array first and then perform a binary search), but, by far the cleanest and best option.
If you are really interested in efficiency, you can create your own list implementation that uses the field in your object as a hash and uses the HashMap as storage. But probably that would be too much.
Then you must change the place where you fill the data from ArrayList to YourCustomList.
Like:
List list = new ArrayList(); fillFromSoap( list );
To:
List list = new MyCustomSpecialList(); fillFromSoap( list );
The implementation will look something like this:
class MyCustomSpecialList extends AbstractList { private Map<Integer, YourObject> internalMap; public boolean add( YourObject o ) { internalMap.put( o.getThatFieldYouKnow(), o ); } public boolean contains( YourObject o ) { return internalMap.containsKey( o.getThatFieldYouKnow() ); }
}
To a large extent, like a HashSet, the problem is that the HashSet relies on a good implementation of the hashCode method, which you probably don't have. Instead, you use the hash “this field you know” as the hash, which is the one that makes one object equal to another.
Of course, implementing a list from scratch is much more complicated than my snippet above, so I say that the Fabian Steeg proposal would be better and easier to implement (although something like that would be more efficient)
Tell us what you did at the end.
OscarRyz Feb 18 '09 at 0:12 2009-02-18 00:12
source share