【问题标题】:How to add element to this array? [duplicate]如何向该数组添加元素? [复制]
【发布时间】:2013-01-28 08:40:43
【问题描述】:

有没有办法在这个数组中添加新项目?

            RowMsg RowMsg_data[] = new RowMsg[] {

                    new RowMsg(R.drawable.ic_launcher, "Message 1"),
                    new RowMsg(R.drawable.ic_launcher, "Message 2"),
                    new RowMsg(R.drawable.ic_launcher, "Message 3"),
                    new RowMsg(R.drawable.ic_launcher, "Message 4")

            };

            // here i want add next one element, for example: RowMsg(R.drawable.ic_launcher, "Message 5")

【问题讨论】:

    标签: java android


    【解决方案1】:

    如果您使用ArrayList,那么您不必重新分配另一个更大的数组并从您的第一个数组复制,这一切都由ArrayList 处理。

    这是documentationArrayList

    【讨论】:

      【解决方案2】:

      没有。您不能向数组添加元素 - 一旦您创建了数组,它的大小就不能改变。

      你最好有一个清单:

      List<RowMsg> messages = new ArrayList<RowMsg>();
      messages.add(new RowMsg(R.drawable.ic_launcher, "Message 1"));
      // etc
      

      顺便说一句,将类型信息保存在一个地方更为传统,并且 Java 变量通常采用驼峰式大小写 - 所以即使您确实坚持使用数组,它也会更好将其声明为:

      RowMsg[] rowMsgData = new RowMsg[] {
          ...
      };
      

      (我还建议避免使用缩写,但我们就这样吧。)

      【讨论】:

        【解决方案3】:

        您无法在初始化后更改数组的大小。使用List 例如ArrayList&lt;RowMsg&gt; 代替。

        【讨论】:

          【解决方案4】:

          如果你真的需要RowMsg_data 成为一个数组

          RowMsg_data = new ArrayList<RowMsg>(Arrays.asList(RowMsg_data))
                         .add(new RowMsg(R.drawable.ic_launcher, "Message 5"))
                         .toArray();
          

          【讨论】:

            【解决方案5】:

            试试

                RowMsg_data = Arrays.copyOf(RowMsg_data, RowMsg_data.length);
                RowMsg_data[RowMsg_data - 1] = new RowMsg(R.drawable.ic_launcher, "Message 5");
            

            【讨论】:

              猜你喜欢
              • 2011-02-20
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-08-03
              • 1970-01-01
              • 2012-03-23
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多