【发布时间】:2016-05-01 18:47:24
【问题描述】:
我创建了两个类。第一个(称为 Class1)有一个私有属性:价格。第二个(称为Class2)需要有一组Class1的对象:
我的代码:
private HashSet set = new HashSet<Class1>();
目标是在 Class2 中创建一个方法,该方法接受一个 int 作为参数并遍历对象以检查,直到找到一个价格等于给定参数编号的对象。它需要返回对象。例如,我想找到一个价格为 500 的对象,所以我调用函数 check(500),它返回的正是那个价格为 500 的对象。我该怎么做?
我的代码:
public Class1 check(int p)
{
Class1 c = new Class1(p);
Iterator it = set.iterator();
while(it.hasNext())
{
// HERE IS THE HELP NEEDED. Using an array it
// would be sth like if(element[i].price == p)
// but I need to use set
if()
{}
it.next();
}
【问题讨论】:
-
如果您只是使用可以从 HashSet 获取的 Stream,则无需(直接)循环。但要获得更好更完整的答案,请创建并发布您的minimal reproducible example 程序——请阅读链接。
-
看看这个:docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html 这是一个增强的 for 循环