Search an attribute inside a Vector on Java
Solution 1
I assume that your problem is that you want to have a method that searches for a result based on some property of the collection type. Java is weak on this because it is best expressed in a language which has closures. What you need is something like:
public interface Predicate<T> {
public boolean evaluate(T t);
}
And then your search method looks like:
public static <T> T findFirst(List<T> l, Predicate<T> p) { //use List, not Vector
for (T t : l) { if (p.evaluate(t)) return t; }
return null;
}
Then anyone can use this general-purpose search method. For example, to search for an number in a vector of Integer
s:
List<Integer> is = ...
findFirst(is, new Predicate<Integer> {
public boolean evaluate(Integer i) { return i % 2 == 0; }
});
But you could implement the predicate in any way you want; for any arbitrary search
Solution 2
Use Collections.binarySearch
and provide a Comparator
.
EDIT: This assumes that the Vector
is sorted. Otherwise, one has to do a linear search.
Comments
-
PotterSys almost 2 years
I've a
Vector
of objects, and have to search inside for a random attribute of those objects (For example, aPlane
class, aVector
containingPlane
; and I've to search sometimes fordestination
, and others topilotName
).I know I can traverse the
Vector
using anIterator
, but I've got stuck at how do I change the comparison made between a String and the attribute on the object. I thought of usingswitch
, but a another opinion would be cool.
Update 1:
The code I've written is something like this (Java n00b alert!):
public int search(String whatSearch, String query){ int place = -1; boolean found = false; for ( Iterator<Plane> iteraPlane = this.planes.iterator(); iteraPlane.hasNext() && found == false; ) { Plane temp = (Plane) iteraPlane.next(); /* Here is where I have to search for one of many attributes (delimited by whatSearch */ } return place; }
Seems I've to stick to linear search (and that's a price I've able to pay). Anyway, I was thinking if Java had something like variable variable name (ouch!)