0
    ListIterator litr = PuntenLijst.listIterator();

    while(litr.hasNext()){
       Object Punt = litr.next();
       Punt.print();
    }

PuntenLijst is an ArrayList that contains object instances from another Class.

Now I have made a method print() that prints out something from that object (of the other class).

With this loop I try to loop through the ArrayList, and then use the print() method from the other class, but it doesn't not seem to be working.

Can anybody help me out?

0

5 Answers 5

3
   Object Punt = litr.next();
   Punt.print();

You need to cast your Punt to appropriate class, of which you have the ArrayList.

Of course print() is not a method of Object class

Suppose you have ArrayList like this: -

ArrayList<YourClass> PuntenLijst

Change your invocation to: -

Object Punt = litr.next();
((YourClass)Punt).print();

Or: -

   YourClass Punt = litr.next();
   Punt.print();
Sign up to request clarification or add additional context in comments.

2 Comments

If the declaration is ArrayList<YourClass> no cast is needed. just do YourClass Punt = litr.next();
@ColinD Oh yeah. I myself forgot that I assumed ArrayList that way.
2

Cast the object you get as response for litr.next() to corresponding type and call method on that type.

Example:

     Punt puntObj =(Punt) litr.next();
       puntObj.print();

Comments

2

Cast Punt to the type that contains the Print() method.

while(litr.hasNext()){
       TYPE_THAT_HAS_PRINT Punt = (TYPE_THAT_HAS_PRINT) litr.next();
       Punt.print();
    }

Comments

0

Why dont you just use for:each loop? The casting is taken care by the JVM provided you've defined PuntenLijst with the correct Type.

Comments

0

You need to cast Object type to the type your actual object is.

1 Comment

maybe. In the code snip provided, Punt is just a variable name. The poster has not provided what types of objects are stored in his list.

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.