gpt4 book ai didi

java - 允许任何 int 值作为索引的数组声明

转载 作者:行者123 更新时间:2023-12-01 19:30:26 25 4
gpt4 key购买 nike

有没有办法声明一个 int 数组 (arr),这样索引 i 可以表示任何数字 <= Integer.MAX_VALUE,该数字无法提前知道。

因此,只要值 <= Integer.MAX_VALUE,arr[i] 就永远不会返回错误

我尝试了int[] arr = new int[Integer.MAX_VALUE],但这需要太多空间并且不可行。

最佳答案

在 Java 中,不可能声明没有大小的数组。您不需要使用数组来为所有未使用的索引占用内存。您需要的是一张 map ,它对于您的用例来说可以节省空间。

    Map<Integer, Object> index = new HashMap<>();

//store
index.put(1, "Value 1");
index.put(2, "Value 2");

//retrieve
index.get(1); //returns: Value 1

关于java - 允许任何 int 值作为索引的数组声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59897071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com