Java:存储到ArrayList的任意索引的最佳方法 [英] Java: Best way to store to an arbitrary index of an ArrayList

查看:96
本文介绍了Java:存储到ArrayList的任意索引的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我不能在尚未使用的ArrayList的索引上存储值,即小于大小。换句话说,如果myArrayList.size()为5,那么如果我尝试执行

  myArrayList.set(10, Hello World)

我会得到一个超出界限的错误。但我的应用程序需要这个。除了在每个中间槽中存储空的循环之外,还有一个更优雅的方式?



它像我看起来像:




  • 在Vector

  • 中的行为是一样的。如果我需要能够随机访问(即pos X中的元素),那么我的选择是Vector和ArrayList。

  • 我可以使用HashMap并使用索引作为关键字,但实际上效率不高。



那么什么是典型的解决方案,看起来像一个普通的情况。我必须缺少一些东西...

解决方案


我可以使用HashMap并使用索引一个关键,但这真的是低效率。


取决于。如果您使用的索引非常稀疏,那么使用Map可能会更好。如果这些指标往往紧密相连,我认为没有更好的方法来填补空值。只需编写一个可以反复使用的实用程序函数,而不是在需要的地方重复循环,就像这样:

  private void padTo(List<?> list,int size){
for(int i = list.size(); i< size; i ++)
list.add(null);
}


I know that I cannot store a value at an index of an ArrayList that hasn't been used yet, i.e. is less than the size. In other words, if myArrayList.size() is 5, then if I try to do

myArrayList.set(10, "Hello World") 

I will get an out of bounds error. But my app needs this. Other than a loop of storing null in each of the intermediate slots, is there a more elegant way?

It looks to me like:

  • This behavior is the same in Vector
  • If I need to be able to randomly access (i.e. element at pos X) then my choices are Vector and ArrayList.
  • I could use a HashMap and use the index as a key but that's really inefficient.

So what is the elegant solution to what looks like a common case. I must be missing something...

解决方案

I could use a HashMap and use the index as a key but that's really inefficient.

Depends. If the indices you use are very sparse, it might be a lot better to use a Map. If the indices tend to be closely together, I think there is no better way than to fill it with nulls. Just write a utility function for it that you can use over and over instead of repeating the loop everywhere you need it, something like this:

private void padTo(List<?> list, int size) {
    for (int i=list.size(); i<size; i++)
        list.add(null);
}

这篇关于Java:存储到ArrayList的任意索引的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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