Is there a more efficient way to add to an Array? - java

Below is a sample of code I am using to add to an array. Basically if I understand correctly currently I am copying an Array into a List, then adding to the list and copying back to an array. It seems like there should be a better way to do this.
List<String> stringList = new ArrayList<String>(Arrays.asList(npMAROther.getOtherArray()));
stringList.add(other);
npMAROther.setOtherArray(stringList.toArray(new String[0]));
I just edited my question for a bit more clarity. The for loop previously seen wasn't exactly needed in regards to my original question. I am simply looking for a more efficient way to add to an array.

If this is something that is done frequently, consider using a list. However...
You can easily add a single element to the end of an array like this.
final String[] source = { "A", "B", "C" };
final String[] destination = new String[source.length + 1];
System.arraycopy(source, 0, destination, 0, source.length);
destination[source.length] = "D";
for(final String s : destination) {
System.out.println(s);
}
You can also make it a method.
public static String[] addToArray(final String[] source, final String element) {
final String[] destination = new String[source.length + 1];
System.arraycopy(source, 0, destination, 0, source.length);
destination[source.length] = element;
return destination;
}

Supposing you want to use an array, not a list and that all the array elements are filled, you would copy the array in an array that has the size of the original array plus the string list size, then append the list elements at the end of the array:
String[] array = npMAROther.getOtherArray();
List<String> listElementsToAppend = marOther.getOtherListList();
int nextElementIndex = array.length;
// Increase array capacity
array = Arrays.copyOf(array, array.length + listElementsToAppend.size());
// Append list elements to the array
for (String other : listElementsToAppend) {
array[nextElementIndex++] = other;
}

There are many ways to combine arrays in O(N) time. You could do something more readable than your code, for instance :
String[] arr1 = {"1", "2"}, arr2 = {"3", "4"};
ArrayList<String> concat = new ArrayList<>(); // empty
Collections.addAll(concat, arr1);
Collections.addAll(concat, arr2);
// concat contains {"1", "2", "3", "4"}

Related

Simplest way to add an item to beginning of an array in Java

I need the simplest way to add an item to the front of an Java array.
I need the Java array NOT the ArrayList.
There are two ways to do this. One, using Objects or another using generics. I recommend you to use generics because gives you more flexibility as you gonna see in these examples.
In this first implementation the function add2BeginningOfArray is using generics:
public static <T> T[] add2BeginningOfArray(T[] elements, T element)
{
T[] newArray = Arrays.copyOf(elements, elements.length + 1);
newArray[0] = element;
System.arraycopy(elements, 0, newArray, 1, elements.length);
return newArray;
}
Calling this function is really simple. For instance, if you have a class Dot and you want to add an element to the beginning of an array of Dot objects you just need to do this:
int size = 20;
Dot[] dots = new Dot[size];
for (int i = 0; i < size; i++) {
dots[i] = new Dot("This is a dot");
}
Dot goal = new Dot("This is a goal");
System.out.println(Arrays.toString(add2BeginningOfArray(dots, goal)));
You can also implement a function declaring the function parameters as Object as shown in this example:
public static Object[] add2BeginningOfArray(Object[] elements, Object element){
Object[] tempArr = new Object[elements.length + 1];
tempArr[0] = element;
System.arraycopy(elements, 0, tempArr, 1, elements.length);
}
Now, what is the problem? Well, not a big problem but now you need to declare your array as Object[] and use this kind of declaration to work with it.
Object[] foo = {"2", "3", "4"};
//adding an element to the beginning array
Object[] numbers = add2BeginningOfArray(foo, "1");
System.out.println(Arrays.toString(numbers));
For me the generics approach is cleaner and more scalable, so I really recommend it over the Object approach.
Apache Commons Lang class 'ArrayUtils' makes this very easy, if that is an option for you:
char[] arrayA = {'b', 'c'};
char[] arrayB = ArrayUtils.add(arrayA, 0, 'a');
// arrayB: [a, b, c]
for(int i = roadVehicles.length; i > 0; i--) {
if (roadVehicles[i-1] != null) {
roadVehicles[i] = roadVehicles[i-1];
}
}
roadVehicles[0] = car;
As per the Java tutorials (which I thoroughly recommend beginners to work through)
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
Because arrays cannot be resized - you can overwrite the first element, but to perform an insert you must create a new array 1 larger than the previous one, put your new element in the first position and fill the rest of the array with the existing elements.
Of course, in practice don't do this. Instead use a collection that suits your actual use-case.
So the actual answer to your question is: The simplest way to add an item to front of a java array is to use a better collection type such as a Deque.
I cannot think of any valid reason in Java to not use a more appropriate collection than a raw array if inserting to the front is required.
Once created an array cannot be resized. If you have to add an element you'll need to create a new array.
If you know the array type it's trivial, but a nicer solution will work with any array type, using the java.lang.reflect.Array
Example code:
public static Object addElementInFrontOfArray(Object array, Object element) {
int newArraySize = Array.getLength(array)+1;
Object newArray = Array.newInstance(element.getClass(), newArraySize);
//Add first element
Array.set(newArray, 0, element);
for (int i=1 ; i<newArraySize; i++) {
Array.set(newArray, i, Array.get(array, i-1));
}
return newArray;
}
Consider that you can pass a int[] array as parameter but a Integer[] arrary will be returned
Considering this source
https://www.journaldev.com/763/java-array-add-elements
you can add new elements at the beginning of you array by doing this:
public static Object[] add(Object[] arr, Object... elements){
Object[] tempArr = new Object[arr.length+elements.length];
System.arraycopy(arr, 0, tempArr, elements.length, arr.length);
for(int i=0; i < elements.length; i++)
tempArr[i] = elements[i];
return tempArr;
}
Why not just use an ArrayList?
You could use an Array convert it to a List as follows:
List<Integer> myList = Arrays.asList(1,2,3);
//Instead of 1,2,3 you could create an Integer array: Integer[] myArray = {1,2,3};
myList.add(0, 25);
If you decide doing this way, you could check the answers of this question:
Java Arrays how to add elements at the beginning
or just check out the documentation:
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
here's a concrete example of the simplest way I could find:
List<StackTraceElement> stack = new ArrayList<StackTraceElement> (Arrays.asList (e.getStackTrace()));
stack.add (0, new StackTraceElement ("class", "method", "file", 25439));
StackTraceElement[] newStack = new StackTraceElement[stack.size()];
newStack = stack.toArray (newStack);
e.setStackTrace (newStack);
Basically it uses java.util.Arrays.asList() to turn the array into a List, adds to the list and then turns the list back into an array with List.toArray().
As everybody has said, you can't really add to the beginning of an array unless you shift all the elements by one first, or as in my solution, you make a new array.
Just .unshift()
This adds an element to the beginning of an array.

add elements to Java Array

Let's say we defined an array with 20 elements. is there any way we can add some objects to the array, without any specific order of course and not just once like String[] t= {"one", "two", ..., "twenty"} ?
String[] t = new String[20];
//I know this won't work
//but something like this:
//t = {"one", "two", "three"}
//and later, add some more
//t = {"four"} ...
There are several ways to initialize the elements in an Array,
String[] t = new String[20];
t[0] = "zero";
t[1] = "one";
You can also use System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) to copy from one to another (if that's what you mean). Here concatenate Array(s) a and b to a new Array c.
String[] a = {"Hello"};
String[] b = {"World"};
String[] c = new String[a.length+b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
System.out.println(Arrays.toString(c));
Output is
[Hello, World]
You cannot change the size of the array, but you can assign elements at specific positions.
t[3] = "four";
Re-ordering and remembering where the array is supposed to end may or may not become cumbersome.
For more flexible "arrays", people like to use java.util.ArrayList.
You can assign values like this
t[10] = "ten";
t[11] = "eleven";
It is better to use ArrayList so there is no need of initializing the size first and it is dynamic too.
Unfortunately, that's not exactly how java arrays work. To instantiate and initialize an array use the syntax...
String[] t = new String[20];
t[0] = "One";
t[1] = "Two";
or,
String[] t = {"One", "Two"};
If you want more control over the array the I'd recommend using an ArrayList object instead where you can add, remove, change, sort the items in the array. For example,
ArrayList t = new ArrayList();
t.add("One");
t.add("Two");
t.remove(0);
ArrayList is a good option for ArrayList supports dynamic arrays that can grow as needed.
With arrays you can add elements by specifying the specific position you want to add
like adding in position 4 we can do something like array[3] = "four"
but for more control arraylist is recommended
Unfortunately, Array should be used in below way only
String[] t = new String[20];
t[0] = "One";
t[1] = "Two";
...
t[19] = "Twenty";
You can try using arrayList: You need not even specify how many elements are expected while initializing.
ArrayList t = new ArrayList();
t.add("One");
t.add("Two");
...
t.add("Twenty");

difference between new String[]{} and new String[] in java

I am fresher in java ,i have a doubt in java
that is
String array= new String[]{};
what is the use of { } here ?
what is the difference between String array=new String[]; and String array=new String[]{};
when I am writing String array=new String[10]{}; got error why?
Help me I am confused.
{} defines the contents of the array, in this case it is empty. These would both have an array of three Strings
String[] array = {"element1","element2","element3"};
String[] array = new String[] {"element1","element2","element3"};
while [] on the expression side (right side of =) of a statement defines the size of an intended array, e.g. this would have an array of 10 locations to place Strings
String[] array = new String[10];
...But...
String array = new String[10]{}; //The line you mentioned above
Was wrong because you are defining an array of length 10 ([10]), then defining an array of length 0 ({}), and trying to set them to the same array reference (array) in one statement. Both cannot be set.
Additionally
The array should be defined as an array of a given type at the start of the statement like String[] array. String array = /* array value*/ is saying, set an array value to a String, not to an array of Strings.
String array=new String[]; and String array=new String[]{}; both are invalid statement in java.
It will gives you an error that you are trying to assign String array to String datatype.
More specifically error is like this Type mismatch: cannot convert from String[] to String
You have a choice, when you create an object array (as opposed to an array of primitives).
One option is to specify a size for the array, in which case it will just contain lots of nulls.
String[] array = new String[10]; // Array of size 10, filled with nulls.
The other option is to specify what will be in the array.
String[] array = new String[] {"Larry", "Curly", "Moe"}; // Array of size 3, filled with stooges.
But you can't mix the two syntaxes. Pick one or the other.
TL;DR
An array variable has to be typed T[]
(note that T can be an arry type itself -> multidimensional arrays)
The length of the array must be determined either by:
giving it an explicit size
(can be int constant or int expression, see n below)
initializing all the values inside the array
(length is implicitly calculated from given elements)
Any variable that is typed T[] has one read-only field: length and an index operator [int] for reading/writing data at certain indices.
Replies
1. String[] array= new String[]{}; what is the use of { } here ?
It initializes the array with the values between { }. In this case 0 elements, so array.length == 0 and array[0] throws IndexOutOfBoundsException: 0.
2. what is the diff between String array=new String[]; and String array=new String[]{};
The first won't compile for two reasons while the second won't compile for one reason. The common reason is that the type of the variable array has to be an array type: String[] not just String. Ignoring that (probably just a typo) the difference is:
new String[] // size not known, compile error
new String[]{} // size is known, it has 0 elements, listed inside {}
new String[0] // size is known, it has 0 elements, explicitly sized
3. when am writing String array=new String[10]{}; got error why ?
(Again, ignoring the missing [] before array) In this case you're over-eager to tell Java what to do and you're giving conflicting data. First you tell Java that you want 10 elements for the array to hold and then you're saying you want the array to be empty via {}.
Just make up your mind and use one of those - Java thinks.
help me i am confused
Examples
String[] noStrings = new String[0];
String[] noStrings = new String[] { };
String[] oneString = new String[] { "atIndex0" };
String[] oneString = new String[1];
String[] oneString = new String[] { null }; // same as previous
String[] threeStrings = new String[] { "atIndex0", "atIndex1", "atIndex2" };
String[] threeStrings = new String[] { "atIndex0", null, "atIndex2" }; // you can skip an index
String[] threeStrings = new String[3];
String[] threeStrings = new String[] { null, null, null }; // same as previous
int[] twoNumbers = new int[2];
int[] twoNumbers = new int[] { 0, 0 }; // same as above
int[] twoNumbers = new int[] { 1, 2 }; // twoNumbers.length == 2 && twoNumbers[0] == 1 && twoNumbers[1] == 2
int n = 2;
int[] nNumbers = new int[n]; // same as [2] and { 0, 0 }
int[] nNumbers = new int[2*n]; // same as new int[4] if n == 2
(Here, "same as" means it will construct the same array.)
Try this one.
String[] array1= new String[]{};
System.out.println(array1.length);
String[] array2= new String[0];
System.out.println(array2.length);
Note: there is no byte code difference between new String[]{}; and new String[0];
new String[]{} is array initialization with values.
new String[0]; is array declaration(only allocating memory)
new String[10]{}; is not allowed because new String[10]{ may be here 100 values};
String array[]=new String[]; and String array[]=new String[]{};
No difference,these are just different ways of declaring array
String array=new String[10]{}; got error why ?
This is because you can not declare the size of the array in this format.
right way is
String array[]=new String[]{"a","b"};
1.THE USE OF {}:
It initialize the array with the values { }
2.The difference between String array=new String[]; and String array=new String[]{};
String array=new String[]; and String array=new String[]{}; both are
invalid statement in java.
It will gives you an error that you are trying to assign String array
to String datatype. More specifically error is like this Type
mismatch: cannot convert from String[] to String
3.String array=new String[10]{}; got error why?
Wrong because you are defining an array of length 10 ([10]), then
defining an array of length String[10]{} 0
Theory above is well explained.
A PRACTICAL USE: Declare an array on the spot for a method parameter.
MyResult result = myMethod(new String[]{"value1", "value2"});

How to add item in array?

I want add item at the top of array?
how can i achieve this?
there are two item in array. i want to add item at top of the array.
result1 = new String[result.length+1];
for(int i=result.length;i==0;i--)
{
if(i==0)
{
result1[0]="Latest";
}
result1[i]=result[i-1];
}
To answer your question: You need to
Create a new array with with size = old length + 1.
Copy the content of the old array to the new array,
Insert "latest" into the new array:
Like this:
String[] result = { "a", "b", "c" };
String[] tmp = new String[result.length+1];
System.arraycopy(result, 0, tmp, 1, result.length);
tmp[0] = "latest";
result = tmp;
But, I encourage you to consider using a List such as ArrayList in which case you could express this as
result.add(0, "latest");
You can't : an array has a fixed length.
If you want to have variable size "arrays", use ArrayList.
Exemple :
ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.set(0, "new a");
for (String s: list) {
System.out(s);
}
But you can use ArrayList and with add(int index, E object) function you can add items wherever you want. And you can convert ArrayList to array[] easly
Use stack which works as LIFO (Last In First Out), hence whenever you pop (read) you will get the latest(at the top) pushed item
Here is the Java code reference using Array: http://wiki.answers.com/Q/Implementing_stack_operation_using_array_representation_with_java_program
One problem with your solution is that when i == 0, you set the value to Latest but the value is overwritten after with result1[i]=result[i-1];
Try
if(i==0) {
result1[0]="Latest";
}
else {
result1[i]=result[i-1];
}

equivalent to push() or pop() for arrays?

I am trying to add, remove and reference items from an array I create in my main java file, but I am having trouble figuring out the correct syntax. In actionscript they have push() and pop() for adding and removing items in an array, is there an equivalent in android?
In Java an array has a fixed size (after initialisation), meaning that you can't add or remove items from an array.
int[] i = new int[10];
The above snippet mean that the array of integers has a length of 10. It's not possible add an eleventh integer, without re-assign the reference to a new array, like the following:
int[] i = new int[11];
In Java the package java.util contains all kinds of data structures that can handle adding and removing items from array-like collections. The classic data structure Stack has methods for push and pop.
For those who don't have time to refactor the code to replace arrays with Collections (for example ArrayList), there is an alternative. Unlike Collections, the length of an array cannot be changed, but the array can be replaced, like this:
array = push(array, item);
The drawbacks are that
the whole array has to be copied each time you push, and
the original array Object is not changed, so you have to update the variable(s) as appropriate.
Here is the push method for String:
(You can create multiple push methods, one for String, one for int, etc)
private static String[] push(String[] array, String push) {
String[] longer = new String[array.length + 1];
for (int i = 0; i < array.length; i++)
longer[i] = array[i];
longer[array.length] = push;
return longer;
}
This alternative is more efficient, shorter & harder to read:
private static String[] push(String[] array, String push) {
String[] longer = new String[array.length + 1];
System.arraycopy(array, 0, longer, 0, array.length);
longer[array.length] = push;
return longer;
}
Use Array list
http://developer.android.com/reference/java/util/ArrayList.html
You can use Arrays.copyOf() with a little reflection to make a nice helper function.
public class ArrayHelper {
public static <T> T[] push(T[] arr, T item) {
T[] tmp = Arrays.copyOf(arr, arr.length + 1);
tmp[tmp.length - 1] = item;
return tmp;
}
public static <T> T[] pop(T[] arr) {
T[] tmp = Arrays.copyOf(arr, arr.length - 1);
return tmp;
}
}
Usage:
String[] items = new String[]{"a", "b", "c"};
items = ArrayHelper.push(items, "d");
items = ArrayHelper.push(items, "e");
items = ArrayHelper.pop(items);
Results
Original: a,b,c
Array after push calls: a,b,c,d,e
Array after pop call: a,b,c,d
You can use LinkedList. It has methods peek, poll and offer.

Categories

Resources