Suppose that i have a List<Person> all
data structure, where Person
is defined as:
class Person {
String firstName;
String secondName;
boolean hasValidDrivingLicense;
}
I want to mantain a redundant List<Person> drivers
that contains only the persons that have a valid driving license. I think it can also be seen as an index (well an index would contain all the items, but the purpose is very similar).
This is to avoid the need for looping through the entire list each time i need those data.
(Looping each time has the advantage that i have a single-authoritative-representation of my hasValidDrivingLicense information; abandoning this road requires: a)valid reasons b)tested alternative. The reasons depend on the specific problem; the alternative is what i'm developing here :-) )
the problem
I probably have something like this:
void add(Person p) {
all.add(p);
if (p.hasValidDrivingLicense()) {
drivers.add(p);
}
}
this often works.
Person p = new Person(); //then set fields, of course.
add(p);
p.setHasValidDrivingLicense(true);
Here it doesn't. So the problem is: redundant information may misalign. Indexes may "broke".
solutions
Problem
Immutability seems to be a viable solution, but, from the collection maintainer point of view, that is the person who writes the code:
public void add(Person p) {
...
}
has to ensure that p is immutable or better, that at least hasValidDrivingLicense is final.
a) this may be done through reflection (http://stackoverflow.com/questions/203475/how-do-i-identify-immutable-objects-in-java) But doesn't this require a new performance evaluation? Doesn't reflection come at a cost?
b) are there, perhaps in design patterns or in new features of the language (eg.annotations) other solutions to this problem?
I guess what you want is a "live" filtered view of your all collection.
This can be done quite nicely with Google Guava and a Predicate:
http://docs.guava-libraries.googlecode.com/git-history/v11.0.2/javadoc/com/google/common/collect/Collections2.html#filter%28java.util.Collection,%20com.google.common.base.Predicate%29
On the other hand, just implementing a List personsWithDriversLicens() {...} is also easy, so perhaps Guava is overkill - depends on your needs, including performance characteristics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With