简体   繁体   中英

ArrayList: How to arraylist.set when you have multiple setters

I currently have 2 classes. My bot:

public class Bot {
    private int X;
    private int Y;
    private int degress;

    public int getX() {
        return X;
    }

    public int getY() {
        return Y;
    }

    public int getDegress() {
        return degress;
    }

    public void setX(int X) {
        this.X = X;
    }

    public void setY(int Y) {
        this.Y = Y;
    }
}

and my main code.. the problem i am having is when trying to set the degrees in my main class. What I am trying to do is something similar to:

bots.set(bots.get(1).getDegress(),+1);

but gives me this error "The method set(int, Bot) in the type ArrayList is not applicable for the arguments (int, int)"

and how my ArrayList looks like

public static ArrayList<Bot> bots = new ArrayList<Bot>();

So to sum it up. How could i come about to change X, Y or Degress with the bots.set?

bots.set is an ArrayList method. To mutate a Bot instance, you must call a Bot method.

It should be:

Bot bot = bots.get(1);
bot.setDegrees(bot.getDegrees()+1);

Or course, you'll need a setDegrees method in your Bot class.

bots.set(bots.get(1).getDegress(),+1); at this line you are calling the Set method of ArrayList class, which is used to replace an element at the specified index in the list. It takes 2 parameters, first the index of the element to be replaced and 2nd the element to be replaced with. So in your case an int and an instance of Bot class.

To set degrees in you Bot class object you'll first have to get it from the list bots and use setDegrees() on the object of bot class(which btw seems to be missing from your Bot class).

bots.get(1).setDegrees(bots.get(1).getDegress()+1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM