基于对象属性的对象数组的子集/索引

时间:2013-04-16 21:01:55

标签: java arrays collections

假设我有一系列对象,如下面的假人[]。我想找到数组对象的索引,其属性为a == 5a > 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会有帮助吗?

1 个答案:

答案 0 :(得分:1)

// 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;
   }
}
相关问题