Java Eclipse建议我将我的方法设为静态

时间:2016-05-21 16:30:32

标签: java arraylist static packages

我有课程PlayerPoliticCardModelPlayerPlayerPoliticCard都有一个ArrayList来存储enum Color的颜色值。我想编写方法DrawCard(),该方法从Color ArrayList获取PoliticCard值,并将其存储在ArrayList Player中。

Eclipse让我将ArrayList的{​​{1}}更改为PoliticCard,但在其他所有帖子中我看到static仅用于不是static的常量这里的情况(ArrayList中的PoliticCard每次玩家使用方法DrawCard()时都会不断变化,因此在ArrayList中有一个静态PoliticCard这里有问题吗?

PS:所有类都在不同的包中(当然我已经在需要的时候全部导入了它们),它与此有关吗?

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);
        }

    }
}

1 个答案:

答案 0 :(得分:3)

  

Eclipse让我将PoliticCard的arrayList更改为static

不是Eclipse强迫你改为静态它是Java编译器。这背后的原因是你的DrawCard方法中的这一行:

PoliticCard.getPoliticCards().remove(i);

您正在尝试使用PoliticCard类而不是PoliticCard实例访问政治卡的getter。这就是为什么吸气剂和磁场都必须是静态的。