查找集合中具有给定属性的所有对象

编程入门 行业动态 更新时间:2024-10-25 07:19:51
本文介绍了查找集合中具有给定属性的所有对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一些复杂的对象,如猫,它有许多属性,如年龄,喜爱的猫食等。

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...

更多推荐

查找集合中具有给定属性的所有对象

本文发布于:2023-10-26 11:53:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530055.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!