如何添加新的元素到一个数组 [英] How to add new element into an array

查看:146
本文介绍了如何添加新的元素到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要移植code从黑莓到Android和面临的小问题:
例:BB code是:

I need to port code from blackberry to android and facing small problem: Example: the bb code is:

public class MyClass{
   private MyObject[] _myObject;

   public void addElement(MyObject o){
      if (_myObject == null){
        _myObject = new MyObject[0];
      }
      Arrays.add(_myObject, o);
   }
}

不幸的是Android不具备 Arrays.add()这是一部分 net.rim.device.api.util.Arrays 静态无效添加(对象[]数组,Object对象)

有没有更换为Android动态扩展,并追加到简单的数组,所以我不会改变我的code的其余部分。

Is there any replacement for android to dynamically extend and append in to simple array so I don't change the rest of my code.

我试着写我自己的工具,但它不工作:

I tried to write my own utility but it does not work:

public class Arrays {
  public static void add(Object[] array, Object object){
    ArrayList<Object> lst = new ArrayList<Object>();
    for (Object o : array){
      lst.add(o);
    }
    lst.add(object);
    array = lst.toArray();
  }
}

..我打电话后,

public void addElement(MyObject o){
      if (_myObject == null){
        _myObject = new MyObject[0];
      }
      Arrays.add(_myObject, o);
   }

_myObject 仍然含有0元素。

推荐答案

是的,因为 _myObject 引用按值传递。你需要使用:

Yes, because the _myObject reference is passed by value. You'd need to use:

public static Object[] add(Object[] array, Object object){
  ArrayList<Object> lst = new ArrayList<Object>();
  for (Object o : array){
    lst.add(o);
  }
  lst.add(object);
  return lst.toArray();
}

...

_myObject = Arrays.add(_myObject, o);

不过,这将是最好只使用的ArrayList&LT; E&GT; 下手...

有了解这里两个重要的事情:

There are two important things to understand here:

的Java的总是的使用传递按值

Java always uses pass-by-value

这是传递的值是一个引用(获得一个对象的一种方式,或者为null)或原始值。这意味着,如果你改变的值的参数的,也不会被调用者看到。如果你改变的东西价值的的对象中的参数值是指的,这是一个不同的问题:

The value which is passed is either a reference (a way of getting to an object, or null) or a primitive value. That means if you change the value of the parameter, that doesn't get seen by the caller. If you change the value of something within the object the parameter value refers to, that's a different matter:

void doSomething(Person person) {
  person.setName("New name"); // This will be visible to the caller
  person = new Person(); // This won't
}

数组是固定大小的Java中

您无法将值加到一个数组。一旦你创建它的大小是固定的。如果你想要一个大小可变的集合(这是一个很常见的要求),你应该使用名单,LT的实现; E&GT; 的ArrayList&LT; E&GT ;

You can't "add" a value to an array. Once you've created it, the size is fixed. If you want a variable-size collection (which is a very common requirement) you should use an implementation of List<E> such as ArrayList<E>.

这篇关于如何添加新的元素到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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