1

假设我有一组对象,例如下面的 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帮助吗?

4

1 回答 1

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;
   }
}
于 2013-04-16T21:06:53.997 回答