jkriss is right, that's how to do it. BUT... there's probably a better way
In your case, you don't say what you're doing with the instances once you've identified them, so I can't be sure what's best.
One thing you might try is having two
ArrayLists, or more. e.g. you might have one called
chairs, one called
tables, and one called
furniture which has everything from
chairs and everything from
tables. Then when you only want to mess with the
chairs you don't need to loop through all the
furniture.
Another better way might be to have a common 'base class' for all the things in your
ArrayList, and to provide a method on each class which does something different.
e.g. instead of this:
Code:
class Cow {
// things to do with Cows go here
}
class Sheep {
// things to do with Sheep go here
}
ArrayList list = new ArrayList();
list.add(new Cow());
list.add(new Cow());
list.add(new Sheep());
list.add(new Sheep());
Iterator it = list.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (obj instanceof Cow) {
println("moo");
}
else {
println("baa");
}
}
// prints:
// moo
// moo
// baa
// baa
It's much better to do something like this:
Code:
class Animal {
void talk() {
println("nothing special");
}
}
class Cow extends Animal {
// Cows have something special to say:
void talk() {
println("moo");
}
}
class Sheep extends Animal {
// Sheep have something special to say:
void talk() {
println("baa");
}
}
ArrayList list = new ArrayList();
list.add(new Cow());
list.add(new Cow());
list.add(new Sheep());
list.add(new Sheep());
Iterator it = list.iterator();
while (it.hasNext()) {
Animal animal = (Animal)it.next();
animal.talk();
}
// prints:
// moo
// moo
// baa
// baa
The basic idea of 'extends' is that everything in your
ArrayList is now of the same basic type -
Animal - and that means you can treat them in the same way, and you don't care what special type they are or what special thing they do.
Once you're comfortable with this idea, you might like to read up on how to use the extra Java keywords
interface and
abstract which can make things clearer, especially when you're working on the same code with other people. They can be thought of as a contract, or promise, to the compiler -
Code:
abstract class Animal {
abstract void talk();
}
Means "I promise that things of type
Animal will have a talk method", for example. Because
Animal is
abstract you can't create it directly, you must provide a subclass which extends
Animal and implements the talk method. Interfaces are very similar but more restrictive on what
Animal can provide for itself, and also a bit fussier to use within Processing.