views:

226

answers:

4

Hi.

I have a list of objects of the same class. The order of the list is not important. What i want to do, is to (using bitwise operations) determine whether i should set some field with an incremental value or not. But the trick is that i want need this operation to return false (must not set field) only for the first element.

for (Obj obj:list){

 if (obj.isZero() (op) some_flag){
   //set field
 }
}

Here are some things that im certain of.

When called on the first element of the list, isZero() will return true.

When called on the rest of the elements, its uncertain. But if called on the second element, isZero() returns true, then it will return true for all the list ([3..last])

Any way of doing this? I dont feel like keeping a counter and incrementing it, but if its THE BEST PRACTICE to do so, then ill do it.

+2  A: 

I think you need a counter

larson4
going with it, im in a rush.Thanks.
Tom
+1  A: 

If isZero isn't guaranteed to return true for elements after the first, then you cannot use it to detect whether an element is not the first element without remembering that there was an occurence of the first element already. So what you ask cannot be done.

You don't need a counter there, though - a simple boolean isFirst = true, reset to false on the first iteration, will do the trick just fine.

Pavel Minaev
+1  A: 

If you need a count of all the elements that return (obj.isZero() (op) some_flag), and all elements after that element will continue to return true after that, then something like the following will work:

int counter = 0;

for (Obj obj : list) {
    if (obj.isZero() (op) some_flag) {
        counter = list.size() - list.indexOf(obj);
        break;
    }
}

Otherwise, if you are not guaranteed that the following elements will be true unless it is the second element, then I would just use a simple counter:

int counter = 0;

for (Obj obj : list) {
    if (obj.isZero() (op) some_flag) {
        counter++;
    }
}
aperkins
+1  A: 

I think a boolean will do, won't it?

boolean notFirst = false;
for (Obj obj : list) {
  if (notFirst) {
    ...
  } else {
    notFirst = true;
  }
}
Sean Owen