【问题标题】:How can I get a value from an Arraylist<String>?如何从 Arraylist<String> 中获取值?
【发布时间】:2015-09-08 21:42:01
【问题描述】:

我正在尝试在特定索引 (82, "ojnfonfw7") 内添加一些字符串 ("oidfb9we923982" as some ID) 但我无法获得它可以工作。

java.lang.IndexOutOfBoundsException: Invalid index 82, size is 1

我认为最好的解释方式是举一些例子,

//MARILYNMANSON
ArrayList<String> mMarilynManson = new ArrayList<String>();

mMarilynManson.add(82,"d5c820e90ab46626aed6fg70038424b63f");
mMarilynManson.add(83,"410862c61aa32b14419c43dsf03e84a42f");
mMarilynManson.add(84,"922e09adc85b9c9dd5bgg75b84d809c5f3");

我试图制作循环以创建直到 100,以及不同的方式,但没有人可以工作......任何朋友可以帮我一把吗?

非常感谢!

【问题讨论】:

  • 向我们展示你的循环代码。

标签: java android arraylist


【解决方案1】:

来自ArrayList API:

IndexOutOfBoundsException - if the index is out of range (index &lt; 0 || index &gt; size())

您的 List 大小为 0,因此您无法在更大的索引处插入元素。

【讨论】:

  • 是的,我知道,但我需要解决它!你能给我一些答案吗?谢谢
【解决方案2】:

如果您想要关联数组的行为,请考虑使用HashMap

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

mMarilynManson.put(82,"d5c820e90ab46626aed6fg70038424b63f");
mMarilynManson.put(83,"410862c61aa32b14419c43dsf03e84a42f");
mMarilynManson.put(84,"922e09adc85b9c9dd5bgg75b84d809c5f3");

【讨论】:

    【解决方案3】:

    如果你真的想这样做,你可以循环到 100 次,然后随心所欲,但它会更慢,并且对于你的用例哈希表会更好

    for(int i = 0;i < 100;i++ ){
       mMarilynManson.add("meme");}
    mMarilynManson.add(82,"d5c820e90ab46626aed6fg70038424b63f");
    

    对于哈希表,您可以像下面这样使用它,这对于您的用例可能会更快更好,因为哈希表有 O(1) 获取时间

    HashTable<Integer,String> table = new HashTable<>();
    table.add(82,"d5c820e90ab46626aed6fg70038424b63f");
    

    【讨论】:

      【解决方案4】:
      while (list.size() < 100) {
              list.add(null);
      }
      

      在任何 add() 调用之前添加此代码。这将确保您不会进入 IndexOutOfBound。然后,您可以尝试 set() 方法而不是代码中的 add(),该方法将替换现有的 null 项,而不是像 add() 那样插入

      【讨论】:

        【解决方案5】:

        您不能在大于列表大小的索引处插入元素。
        来自 ArrayList api:“抛出: IndexOutOfBoundsException - 如果索引超出范围 (index size())" https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#add-int-E-

        相反,您可以使用HashMap:

        HashMap<Integer,String> mMarilynManson = new HashMap();
        mMarilynManson.put(82, "ojnfonfw7");
        

        注意:Java 会自动将您的 int 原语 82 自动装箱为 Integer 对象 (http://docs.oracle.com/javase/7/docs/technotes/guides/language/autoboxing.html)

        【讨论】:

          猜你喜欢
          • 2016-08-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-05
          • 2014-01-02
          • 2012-06-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多