Kid Diamond
Kid Diamond

Reputation: 2301

Use method from another class on ArrayList with foreach loop?

public void verschuif1(){
    for(Object x : puntenLijst){
        x.verschuif2(3, 3);
    }
}

puntenLijst is an ArrayList of object instances from another class. Now I tried to do something with a foreach loop that loops through all objects in the ArrayList and uses the method verschuif2() (from an other class) on it.

But it doesn't seem to be working.

Can anybody help me out?

Thanks a lot!

Upvotes: 0

Views: 1130

Answers (3)

Reimeus
Reimeus

Reputation: 159784

You would have to cast your objects first:

for (Object x : puntenLijst){
    ((MyObject)x).verschuif2(3, 3);
}

Alternatively, you could use generics in your ArrayList. So for an ArrayList like this:

ArrayList<MyObject> puntenLijst

You could avoid casting altogether:

for (MyObject x : puntenLijst){
   x.verschuif2(3, 3);
}

Related: Why use Generics

Upvotes: 6

pauljwilliams
pauljwilliams

Reputation: 19225

The problem is that your loop operates on Object references. If your method isnt declared in Object your code has no way of knowing that the method call is valid.

Wht you need is for puntjenblist to be declared similarly to this:

Collection where {type} is some class that declares the versschuif2 method.

Then in your for loop you can reference objects via {type} in order to call that method.

That way the for loop know that every object in the collection has that method that can be called.

Upvotes: 0

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

You need to cast before invoking the method

((ClassName) x).verschuif2(3, 3); 

to make it compile.

Better than that is to make your list generic

List<ClassName> puntenLijst = new ArrayList<ClassName>();

then you won't need to cast (which is considered type unsafe). Then you would loop as follows

for (ClassName x : puntenLijst){ 
    x.verschuif2(3, 3); // no casting required
} 

Upvotes: 0

Related Questions