问题描述
我有一些复杂的对象,如猫,它有许多属性,如年龄,喜爱的猫食等。
I have some complicated object, such as a Cat, which has many properties, such as age, favorite cat food, and so forth.
一组猫存储在Java集合中,我需要找到所有3岁的猫,或者喜欢猫食的是Whiskas。当然,我可以写一个自定义方法,找到那些具有特定属性的猫,但这会带来很多属性很麻烦;是否有一些通用的方法这样做?
A bunch of Cats are stored in a Java Collection, and I need to find all the Cats that are aged 3, or those whose favorite cat food is Whiskas. Surely, I can write a custom method that finds those Cats with a specific property, but this gets cumbersome with many properties; is there some generic way of doing this?
推荐答案
你可以编写一个方法接受一个接口的实例, code> check(Cat)方法,该方法可以通过任何属性检查实现。
You could write a method that takes an instance of an interface which defines a check(Cat)
method, where that method can be implemented with whatever property-checking you want.
make it generic:
Better yet, make it generic:
public interface Checker<T> {
public boolean check(T obj);
}
public class CatChecker implements Checker<Cat> {
public boolean check(Cat cat) {
return (cat.age == 3); // or whatever, implement your comparison here
}
}
// put this in some class
public static <T> Collection<T> findAll(Collection<T> coll, Checker<T> chk) {
LinkedList<T> l = new LinkedList<T>();
for (T obj : coll) {
if (chk.check(obj))
l.add(obj);
}
return l;
}
当然,像其他人一样,这是关系数据库for ...
Of course, like other people are saying, this is what relational databases were made for...
这篇关于查找集合中具有给定属性的所有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!