This site requires JavaScript, please enable it in your browser!
Greenfoot back
dms
dms wrote ...

2014/3/19

How to use an object off a java.util.List?

dms dms

2014/3/19

#
As a beginner i got stuck with the use of the List interface. I managed to get a list of some objects which i try to change in some way (e.g. change the color). Using getIntersectingObjects(MyClass.class) fills my list "selected", which i can print out for tests as "MyClass@6c565c85, MyClass@4f8423fb" and so on. By looping through the list: for (int i = 0; i < selected.size(); i++) { System.out.println(selected.get(i)); } i succsessfully print out individual objects (names?). But: is there any way to use this "names" (or another way) to manipulate the selected objects with their own methods?
lordhershey lordhershey

2014/3/20

#
You can use instance of to test to see what kind of object it is. Then you do something like
SomeObject thing = (SomeObject) PlainObjectFromList;
thing.theMethodYouWantToUse();
This called type casting. You must assign object to a reference of a certain type to be able to call its methods since the compiler will not let you call methods that do not belong to the base object type. If you cast to the wrong object type you will get a run time exception.
danpost danpost

2014/3/20

#
I think the problem you are having can be explained better. I believe that you are having problems with running a method of the class MyClass on the objects contained in your 'selected' list. What you are looking for is:
for (Object obj : selected) // iterate through the list
{
    ((MyClass)obj).myClassMethod(); // run method on objects from list
}
You should not need the use of the 'instanceof' keyword if all the objects in your list are MyClass objects.
danpost danpost

2014/3/20

#
You could also try the following, which would not require you to create a declared List object (unless you still need the list after calling the method on each MyClass object in it and it cannot be done right there within the loop):
for (Object obj : getIntersectingObjects(MyClass.class))
{
    System.out.println(obj)
    ((MyClass) obj).myClassMethod();
}
You need to login to post a reply.