How To Add New Element Into An Array
Solution 1:
Yes, because the _myObject
reference is passed by value. You'd need to use:
publicstaticObject[] add(Object[] array, Objectobject){
ArrayList<Object> lst = newArrayList<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:
voiddoSomething(Person person) {
person.setName("New name"); // This will be visible to the caller
person = newPerson(); // 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>
.
Solution 2:
- commons-lang has
ArrayUtils.add(..)
- guava has
ObjectArrays.concat(..)
.
Here's the code of ObjectArrays.concat(object, array)
:
publicstatic <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.
Post a Comment for "How To Add New Element Into An Array"