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

2014/3/4

ArrayList Method Problems

JetLennit JetLennit

2014/3/4

#
Hi there, I have some code which is basically like this
public void changeX(ArrayList a)
{
    for(int i = a.size() - 1; i >= 0; i--)
    {
         a.get(i).x = a.get(i).x + 10;
    }
}
But then, since it doesn't know there is an int called x in said arraylist it won't work... I know I could just do what i am trying to do for each individual ArrayList but having something like that method would be a lot easier. Does anyone know how do do this?
davmac davmac

2014/3/4

#
Specify the type of element in the ArrayList:
    public void changeX(ArrayList<MyThing> a)   // here!
    {  
        for(int i = a.size() - 1; i >= 0; i--)  
        {  
             a.get(i).x = a.get(i).x + 10;  
        }  
    }  
Then the type of the elements is known, and the x field will be visible to the compiler.
JetLennit JetLennit

2014/3/4

#
But then i wanted multiple types of ArrayLists to work with the same method
danpost danpost

2014/3/5

#
These multiple types, are they all Actors? of these classes that do have an 'x' field, do they all have a common superclass between them and Actor (or World -- or something else)? what is the 'x' field used for?
JetLennit JetLennit

2014/3/5

#
It isn't in greenfoot... and that is just an example. It is more like this
public void scroll(ArrayList b)
{
               for(int i = b.size() - 1; i >= 0; i--) {
			if(dir == 0) b.get(i).setX(b.getX() - 5);
			if(dir == 1) b.get(i).setX(b.getX() + 5);
			g.drawImage(b.get(i).getImage(), b.get(i).getX(), b.get(i).getY(), this);
		}
}
danpost danpost

2014/3/5

#
Still, you could have all your scrollable objects extend a class called 'Scrollable' and put the related methods and fields in it. Then you would typecast any list to 'java.util.List<Scrollable>' and be able to access the methods.
davmac davmac

2014/3/5

#
You could also have the list be a wildcard type:
    public void scroll(ArrayList<? extends Scrollable> b)  
    {  
        for(int i = b.size() - 1; i >= 0; i--) {  
            if(dir == 0) b.get(i).setX(b.getX() - 5);  
            if(dir == 1) b.get(i).setX(b.getX() + 5);  
            g.drawImage(b.get(i).getImage(), b.get(i).getX(), b.get(i).getY(), this);  
        }  
    }  
Then, as long as your classes implement (or extend) "Scrollable", you can use a list of that type as the parameter value.
You need to login to post a reply.