问题描述
我有一些复杂的对象,比如一个 Cat,它有很多属性,比如年龄、最喜欢的猫食等等.
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 的猫.当然,我可以编写一个自定义方法来查找具有特定属性的 Cats,但是这对于许多属性来说变得很麻烦;有没有一些通用的方法来做到这一点?
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?
推荐答案
您可以编写一个方法,该方法接受一个接口的实例,该接口定义了一个 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.
更好的是,让它通用:
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;
}
当然,正如其他人所说,这就是关系数据库的用途...
Of course, like other people are saying, this is what relational databases were made for...
这篇关于在集合中查找具有给定属性的所有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!