【问题标题】:Switching from Array to ArrayList从数组切换到数组列表
【发布时间】:2020-10-05 22:32:54
【问题描述】:

我有一些代码要转换为使用数组列表。

如何在数组中随机生成数字

当我使用数组时:

public void generateNumbers() {

        Random rand = new Random();

        for (int i = 0; i < numbersArray.length; i++ ) {
            numbersArray[i] = rand.nextInt((50 - 1) + 1) + 1;
        }   

    } //generateNumbers()

ArrayList 中有没有等价的array[i]?

【问题讨论】:

    标签: java arrays arraylist data-structures


    【解决方案1】:

    您可以使用 Stream API 生成随机值的数组或列表:

    public static List<Integer> getRandomList(int size, int maxValue) {
    
        Random random = new Random();
        return IntStream.range(0, size)
                        .map(x -> 1 + random.nextInt(maxValue))
                        .boxed()
                        .collect(Collectors.toList());
    }
    

    同样可以生成数组:

    public static int[] getRandomArray(int size, int maxValue) {
    
        Random random = new Random();
        return IntStream.range(0, size)
                        .map(x -> 1 + random.nextInt(maxValue))
                        .toArray();
    }
    

    【讨论】:

    • 在“高效”系统中,我可能更喜欢这个解决方案,唯一的调整是我返回一个 IntStream 而不是 List 或 int[],但对于初学者来说,这可能有点难以承受。
    【解决方案2】:
        Random rand = new Random();
        int listSize = 5;
        List<Integer> numbersList = new ArrayList<>(5)
        for (int i = 0; i < listSize; i++ ) {
            numbersList.add(rand.nextInt());
        }   
    

    数组和列表的工作方式不同。数组具有静态大小,而列表会随着添加的每一项而增加其大小。

    【讨论】:

      【解决方案3】:

      目前还不清楚你的问题是什么,所以我将解决你最后提出的直接问题:

      ArrayList 中有没有等价的array[i]?

      这取决于你用它做什么。您将使用nameOfArrayList.set(i, *value*) 设置值,并使用nameOfArrayList.get(i) 检索值。 ArrayList 类中还有很多方法。我强烈建议您阅读documentation

      您还需要注意ArrayLists 不像数组那样工作。前者是可变的,而后者不是。你可以阅读它here

      【讨论】:

        猜你喜欢
        • 2011-12-19
        • 1970-01-01
        • 2016-10-19
        • 2014-07-04
        • 1970-01-01
        • 2019-03-23
        • 1970-01-01
        • 2021-05-08
        • 1970-01-01
        相关资源
        最近更新 更多