Java ArrayList给了我一个不安全的操作警告



我最近开始做一个个人项目来测试我(糟糕的)java技能。这是一款名为"Go Fish!"的基本Java纸牌游戏。我目前只使用基本的主机输入/输出来制作游戏。但是每当我编译MainClass类时,编译器就会给我"未检查或不安全"的操作警告。我一直在网上寻找解决方案,并尝试了很多,但它总是给我这个错误。

有什么办法可以解决这个问题吗?代码:Class MainClass
    import java.util.*;
public class MainClass
{
    //Playing states
    public static final int PLAYING = 0;
    public static final int OVER = 1;
    //Chance states
    public static final int PLAY = 0;
    public static final int COMP = 1;
    //Win conditions.
    public static final int PLAY_WIN = 0;
    public static final int COMP_WIN = 1;
    //Values used in the game, VERY IMPORTANT
    public static int currentState, currentPlayer;
    public static int winner;
    public static ArrayList<String> Player_Cards;
    public static ArrayList<String> Comp_Cards;
    public static ArrayList<String> Deck_Cards;
    public MainClass() {
    }
    public static void main(String[] args) {
        //Start Game. This action is carried out EVERYTIME the game is started.
        initGame();  //Serves function for "Initializing" the game i.e. sorting cards, distributing, identifying.
    }
    public static void initGame() {
        //Goto Shuffler, get a shuffled deck, return here.
        Shuffler shuffle = new Shuffler();
        Deck_Cards = new ArrayList<String>(shuffle.doShuffle()); //For safe usage.
        Player_Cards = new ArrayList<String>();
        Comp_Cards = new ArrayList<String>();
        //Give player cards        
        for(int i = 0; i < 5; i++) {
            int c = Deck_Cards.size() - 1 - i;
            Player_Cards.add(Deck_Cards.get(c));
            Deck_Cards.remove(c);
        }
        //Give computer cards       
        for(int i = 0; i < 5; i++) {
            Comp_Cards.add(Deck_Cards.get(i));
            Deck_Cards.remove(i);
        }      
        System.out.println("Darp");
    }
}

代码:Class Shuffler:

import java.util.*;
public class Shuffler
{
    public enum Suits {HEARTS, DIAMONDS, CLUBS, SPADES};
    public enum Ranks {ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING};
    public Shuffler() {
    }

    public static ArrayList doShuffle() {
        //Initialize cards
        int count = 0;
        ArrayList<String> deck = new ArrayList<String>();
        for(int i = 0; i < 4; i++) {
            for(int y = 0; y < 13; y++) {
                deck.add("Card is " + Ranks.values()[y] + " of " + Suits.values()[i]);
                count++;
            }
        }
        Collections.shuffle(deck);
        return deck;
    }
}

附加信息:

我在这个项目中使用BlueJ

您为doShuffle方法使用原始类型,因此编译器会抱怨缺乏类型安全。替换

public static ArrayList doShuffle() {

public static List<String> doShuffle() {

使用Shuffler的实例访问该方法,因此可以省略static关键字

这是因为您正在为doShuffle使用原始ArrayList。局部变量已经正确地参数化了,因此将<String>添加到返回类型中应该可以达到目的。

这是因为doShuffle方法返回的是一个泛型的ArrayList。

在main中,你调用那个方法,把结果放在一个数组列表中,这样编译器就会告诉你这个转换是未检查的。

你可以修改返回数组列表的方法,也可以在main中使用泛型数组列表。

p。第一个回答!xD

相关内容

最新更新