我想在 Java 中使用关于随机索引的索引 [英] I want to use index about randomly index in Java

查看:22
本文介绍了我想在 Java 中使用关于随机索引的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Java.当我在 Java 中使用 ArrayList 时.如果我随机访问索引号.

I use Java. when I use ArrayList in Java. if I access index number randomly.

这可行吗?

如果这是不可能的.我该怎么办?

If this is not posible. How should I do?

例如

ArrayList<String> al = new ArrayList<String>();
al.add(100,"stackoverflow");

这可行吗?

推荐答案

您似乎需要的不是 arrayList 而是整数和字符串之间的映射:

What you seem to need isn't an arrayList but a map between integers and strings :

HashMap<Integer,String> mymap = new HashMap<Integer,String>();

所以你可以写

mymap.put(100,"stackoverflow");

还有

String myString = mymap.get(100);

补充为什么不能使用数组列表:

Adding onto why you cannot use an arraylist:

当您第一次初始化 ArrayList 时,大小为零.尝试在大于大小的索引处添加仍然会像数组一样抛出 IndexOutOfBounds 异常.ArrayList 的好处是它会在大小填满时动态分配更多内存.

When you first initialize an ArrayList, the size is zero. Attempting to add at an index that is larger than the size will still throw an IndexOutOfBounds exception just like an array would. The benefit of the ArrayList is that it will dynamically allocate more memory should the size fill up.

此外,即使您努力管理大小以避免错误,数组对于稀疏数组"也不是很有效.

Besides, arrays aren't efficient for "sparse arrays" even if you make the effort to manage the size to avoid errors.

这篇关于我想在 Java 中使用关于随机索引的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆