1

Let's say I have an array of objects like dummies[] below. I want to find the index of array objects where their attribute a == 5 or a > 3 etc.

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? 
  }
}

Is there any way other than iterating over the array objects and check for the conditions? Does using ArrayList or other type of Collection help here?

3
  • You will need to iterate through the array and add matching value dummies to a new array. Commented Apr 16, 2013 at 21:05
  • A simple iteration will let you find a given item, but a better question is why do you want the index? Or are you actually looking for the object that has a==5? Commented Apr 16, 2013 at 21:14
  • I need the indices because I am keeping a table of associations. There is a second array whic has objects which encompass only "a" variable. I need to match them with the objects in this array and do some calculations. a==5 is just an example. I have a range of values. Commented Apr 17, 2013 at 13:05

1 Answer 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;
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.