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

2011/12/1

Problem accessing methods from a List

mal mal

2011/12/1

#
Hi There, W're under pressure to finish a side scrolling game for college. I'm working on a world that randomly builds itself as the player is playing. I've got a good plan, but I'm having trouble getting access to methods that are contained within a list, here's my code:
public SpaceWorld()
    {    
        super(1100, 600, 1, false);  
        currentBackground.drawImage(backgroundWorld, 0, 0);
        setBackground(currentBackground);
        addObject(new SpaceShip (), 70, 150);
        int x = 0;
        
        addObject(new Block(), 200,200);
        addObject(new Block(), 200,222);
        List blockList = getObjects(Block.class);
        
        System.out.println("blocklist size = " + blockList.size()); // print the size of the list to the terminal

        for(int b= 0; b < blockList.size(); b++){
            
            blockList.get(b).setImage(spriteFactory.getBlock(3));
            blockList.get(b).activateType();
        }

I had the code within the for loop on one line, and was getting the error saying it couldn't find the method activateType, so I moved that section to the next row and replaced it with the int 3 for testing purposes, then I get the error "cannot find the method setImage()". This class extends Actor so it has setImage() and I wrote activateType() myself so that's there too, there's another method called getType() which it also says isn't there. Any ideas?
davmac davmac

2011/12/1

#
The plain List get() method returns an Object - which doesn't contain the methods setImage() and activateType(), so you get a compiler error, even though you know in this case that the Object returned will actually be an instance of Block. You can either cast the result to the desired type (line 17 and 18): ((Block)blockList.get(b)).setImage(spriteFactory.getBlock(3)); ((Block)blockList.get(b)).activateType(); Or, you can change the type of the List (line 11): List<Block> blockList = (List<Block>) getObjects(Block.class); Edit: you don't need the cast in this case, just use: List<Block> blockList = getObjects(Block.class);
mal mal

2011/12/1

#
OK, I'll give that a go, thankyou. Is this a problem with List then? As I can call methods in the manner above from both arrays and array lists without any problems
davmac davmac

2011/12/1

#
As I can call methods in the manner above from both arrays and array lists without any problems
Err, no you can't. If you have an array of Object, you can't get an element and then call methods from another class without first casting (of course it works fine if the array is of the actual class type). An ArrayList will exhibit the exact same issue as List. (In fact, List is just an interface, which ArrayList implements).
mal mal

2011/12/1

#
Ah right, that makes sense. Thank you!
You need to login to post a reply.