假设我有一个像下面的 dummies[] 这样的对象数组。我想找到其属性 a == 5
或 a > 3
等的数组对象的索引。
class Dummy{
int a;
int b;
public Dummy(int a,int b){
this.a=a;
this.b=b;
}
}
public class CollectionTest {
public static void main(String[] args) {
//Create a list of objects
Dummy[] dummies=new Dummy[10];
for(int i=0;i<10;i++){
dummies[i]=new Dummy(i,i*i);
}
//Get the index of array where a==5
//??????????????????????????????? -- WHAT'S BEST to go in here?
}
}
除了迭代数组对象并检查条件之外,还有其他方法吗?使用ArrayList
或其他类型的Collection
在这里有帮助吗?
最佳答案
// Example looking for a==5
// index will be -1 if not found
int index = -1;
for( int i=0; i<dummies.length; i++ ) {
if( dummies[i].a == 5 ) {
index = i;
break;
}
}
关于java - 基于对象属性的对象数组的子集/索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16047010/