Reputation: 29
I have the classes Player
, PoliticCard
and ModelPlayer
. Both Player
and PoliticCard
have an ArrayList
to store color values from the enum Color
. I want to write the method DrawCard()
that takes a Color
value from the ArrayList
of PoliticCard
and stores it in the ArrayList
of Player
.
Eclipse made me change the ArrayList
of PoliticCard
to static
but in every other post I've seen static
is only used for constants which is not the case here (the ArrayList
in PoliticCard
is gonna change constantly every time each player uses the method DrawCard()
) so is having a static ArrayList
in PoliticCard
gonna be a problem here?
PS: All the classes are in different packages (of course i have imported them all when needed), it has something to do with this?
public enum Color {
RED, GREEN
}
public class PoliticCard {
private Color cardColor;
private static ArrayList<Color> politicCards;
public PoliticCard() {
int i = 0;
while (i < 13) {
politicCards.add(Color.RED);
i++;
}
while (i < 26) {
politicCards.add(Color.GREEN);
i++;
}
}
public static ArrayList<Color> getPoliticCards() {
return politicCards;
}
}
public class Player {
private int id;
private ArrayList<Color> politicCards;
public Player(int id) {
this.setId(id);
}
public ArrayList<Color> getPoliticCards() {
return politicCards;
}
}
public class ModelPlayer {
public void Player(Player player) {
int i = 0;
while (i < 10) {
new Player(i);
}
}
public void DrawCard(Player player) {
int i = 0;
if (PoliticCard.getPoliticCards().get(i) != null) {
player.getPoliticCards().add(PoliticCard.getPoliticCards().get(i));
PoliticCard.getPoliticCards().remove(i);
} else {
i++;
player.getPoliticCards().add(PoliticCard.getPoliticCards().get(i));
PoliticCard.getPoliticCards().remove(i);
}
}
}
Upvotes: 0
Views: 136
Reputation: 4644
Eclipse made me change the arrayList of PoliticCard to static
It wasn't the Eclipse that have forced you to change to static it was the Java Compiler. And the reason behind this is this line in your DrawCard method:
PoliticCard.getPoliticCards().remove(i);
You are trying to access getter for politics cards using class PoliticCard instead of instance of PoliticCard. And that's why both getter and the field must be static.
Upvotes: 3