获取对象是否部分匹配的布尔值 (Java)
我认为这是一个简单的问题,如果我能找出描述它的搜索词。它类似于 查找集合中具有给定属性的所有对象,只是我只想布尔值“是否存在”结果。
假设我有一个排序的猫 TreeSet,每只猫都有名字、年龄、食物等。对于每个潜在的猫名字,我都有一些复杂的事情要做,但如果我的 TreeSet 中已经有一只猫,我想跳过它姓名。我不在乎其他属性是否匹配。我显然不能这样做 if (!AlltheCats.contains(candidateName))...
因为这样我就会在字符串 CandidateName 和对象 Cat 之间出现类型不匹配。但我不认为我可以创建一个对象来搜索相同的匹配项,因为我不关心年龄、食物等的值。
什么是有效/优雅的方法来做到这一点?
I think this is an easy question, if I could figure out search terms to describe it. It's similar to Finding all objects that have a given property inside a collection except I just want a Boolean "is it there" result.
Say I have a sorted TreeSet of Cats, each of which has a name, age, food, etc. I have something complicated to do for each potential cat name, but I want to skip it if there already a cat in my TreeSet with that name. I don't care if any of the other attributes match. I obviously can't do if (!AlltheCats.contains(candidateName))...
because then I'll have a type mismatch between the string candidateName and the object Cat. But I don't think I can create an object to search for an identical match to, because I don't care about the values for age, food, etc.
What would be an efficient/elegant way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建包含名称的字符串的 HashSet ,每次对一只猫调用方法时,首先检查它是否已经在集合中,如果是,则跳过这只猫。当你继续前进时修改这个集合。
(*)此答案假设您想要为一只具有相同名称的猫 [而不是 0] 调用该方法。
应该看起来像这样:
Create a HashSet of Strings containing names, every time you invoke your method on a cat, check first if it is already in the set, and if it is, skip this cat. Modify this set as you keep going.
(*)This answer assumes you want to invoke the method for one cat [and not 0] with identical name.
Should look something like that: