java - 如何从公共(public)方法/函数返回 ArrayList

标签 java arraylist

<分区>

public static getDeck(ArrayList<Integer> cards) {
    for (int total = 1; total !=5; total++) {
        for (int suit = 1; suit != 14; suit++) {
            cards.add(suit);
        }
    }
    Collections.shuffle(cards); // Randomize the list
    return cards;
}

public static void main(String[] args) {
    // Create the cards here.
    ArrayList<Integer> cards = new ArrayList<>();
    cards = getDeck(cards);
}

我希望能够调用函数 getDeck,它将 52 个数字添加到我传递给它的 Arraylist。在这种情况下卡。然后返回此对象并将其设置为卡片。

我得到的错误是这样的。

enter image description here

最佳答案

getDeck 没有返回类型,您需要将其指定为 ArrayList<Integer>或您的情况下的任何父类(super class)型

public static ArrayList<Integer> getDeck(ArrayList<Integer> cards) {
    for (int total = 1; total !=5; total++) {
        for (int suit = 1; suit != 14; suit++) {
            cards.add(suit);
        }
    }
    Collections.shuffle(cards); // Randomize the list
    return cards;
}

关于java - 如何从公共(public)方法/函数返回 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21970441/

相关文章:

java - 数组中以字符串开头的单词

java - 按钮取消 JFileChooser 单击时仍加载文件

java - 仅获取数组中的名字

java - 如何对 ArrayList(不是数组)的列表进行排序?

android - 将 ArrayAdapter 转换为 List<String>

java - 如何显示在 html 中存储为字符串数组的图像?

java.lang.IllegalStateException : Connection pool shut down exception from spring-integration-aws library

java - 为什么默认的Spring Security策略是AffirmativeBased?

java - 使用 Scanner 时出现 ArrayList IndexOutOfBoundsException

java - 如何创建(然后获取元素)列表的数组/列表?