0
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!

1
  • maybe the compiler doesn't understand Dutch? Commented Oct 16, 2012 at 22:29

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

0

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
} 

Comments

0

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.

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.