开发者

How to add new element into an array [duplicate]

This question already has answers here: How to add new elements to an array? (20 answers) Closed 8 years ago.

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);
   }
}

unfortunately android does not have Arrays.add() which is part of net.rim.device.api.util.Arrays (static void add(Object[] array, Object object))

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();
  }
}

.. after I call

public void addElement(MyObject o){
      if (_myObject == null){
        _my开发者_JAVA百科Object = new MyObject[0];
      }
      Arrays.add(_myObject, o);
   }

the _myObject still contain 0 elements.


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);

However, it would be better to just use an ArrayList<E> to start with...

There are two important things to understand here:

Java always uses pass-by-value

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
}

Arrays are fixed-size in Java

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>.


  • commons-lang has ArrayUtils.add(..)
  • guava has ObjectArrays.concat(..).

Here's the code of ObjectArrays.concat(object, array):

public static <T> T[] concat(@Nullable T element, T[] array) {
    T[] result = newArray(array, array.length + 1);
    result[0] = element;
    System.arraycopy(array, 0, result, 1, array.length);
    return result;
  }

The apache-commons code is a bit longer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜