add elements to Java Array - java

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

Related

what is the data type that i want to use when merging Array when i merge String array and Integer Array into merge Array

I have an String Array and Integer Array,
String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};
I want two merge them into another array.What is the data type of merge Array?and how i implement merge Array?
In Java, String and Integer both are inherited from Object. So you can use Object type to define a general array.
String[] strArray = { "a", "b", "c" };
Integer[] intArray = { 1, 2, 3 };
Object[] arr = new Object[strArray.length + intArray.length];
int j = 0;
for (int i = 0; i < strArray.length; i++) {
arr[j++] = strArray[i];
}
for (int i = 0; i < intArray.length; i++) {
arr[j++] = intArray[i];
}
The first instinct would be to me:
In Java you just can have one Type for container, if you want to mix two types, you have to create some abstraction, like an Interface, or create another way to relate your String with your Integer.
But
consider the #kimdung answer if you just want to mix the two arrays and just this, and if you don't care anything else.
You need to use object type array, as in your case you are using integer wrapper object and string, which can be merge as object in java
Make a Sting array and merge both into that array, you will have to convert Integer to String while merging and the converse when you are retrieving for any purpose
for(int i=0; i<intArray.length; i++) {
mergerArray[i] = String.value(intArray[i]);
}
It is not possible to join two arrays of difference types. But I want to recommend you to use instances java.util.ArrayList instead of array. For example you can join these two different arrays.
ArrayList<Character> strArr= new ArrayList<Character>();
strArr.add(new Character('a'));
strArr.add(new Character('b'));
strArr.add(new Character('c'));
ArrayList<Character> intArr= new ArrayList<Character>();
intArr.add(new Character('1'));
intArr.add(new Character('2'));
intArr.add(new Character('3'));
//merge two arrays
strArr.addAll(intArr);
You can use System.arraycopy();
String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};
Object[] objArray = new Object[strArray.length + intArray.length];
System.arraycopy( strArray, 0, objArray, 0, strArray.length );
System.arraycopy( intArray, 0, objArray, strArray.length, intArray.length );
Rather than type Object, you can change to desired type like String.

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.

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

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"}

Add multiple numbered objects to ArrayList

Suppose I have a lot of String Variables(100 for example):
String str1 = "abc";
String str2 = "123";
String str3 = "aaa";
....
String str100 = "zzz";
I want to add these String variables to ArrayList, what I am doing now is
ArrayList<String> list = new ArrayList<String>();
list.add(str1);
list.add(str2);
list.add(str3);
...
list.add(str100);
I am curious, is there a way to use a loop? For example.
for(int i = 1; i <= 100; i++){
list.add(str+i)//something like this?
}
Use an array:
String[] strs = { "abc","123","zzz" };
for(int i = 0; i < strs.length; i++){
list.add(strs[i]); //something like this?
}
This idea is so popular that there's built-in methods to do it. For example:
list.addAll( Arrays.asList(strs) );
will add your array elements to an existing list. Also the Collections class (note the s at the end) has static methods that work for all Collection classes and do not require calling Arrays.asList(). For example:
Collections.addAll( list, strs );
Collections.addAll( list, "Larry", "Moe", "Curly" );
If you just want a list with only the array elements, you can do it on one line:
List<String> list = Arrays.asList( strs );
Edit: Many other classes in the Java API support this addAll() method. It's part of the Collection interface. Other classes like Stack, List, Deque, Queue, Set, and so forth implement Collection and therefore the addAll() method. (Yes some of those are interfaces but they still implement Collection.)
If you are using Java 9 then easily you can add the multiple String Objects into Array List Like
List<String> strings = List.of("abc","123","zzz");
If you want to stick to good practice, declare your Strings in an array:
String[] strs = new String[]{ "abc", "123", "aaa", ... };
for (String s : strs) // Goes through all entries of strs in ascending index order (foreach over array)
list.add(s);
If strX would be class fields then you could try using reflection - link to example of accessing fields and methods.
If it is local variable then you can't get access to its name so you will not be able to do it (unless str would be array, so you could access its values via str[i] but then you probably wouldn't need ArrayList).
Update:
After you updated question and showed that you have 100 variables
String str1 = "abc";
String str2 = "123";
String str3 = "aaa";
//...
String str100 = "zzz";
I must say that you need array. Arrays ware introduced to programming languages precisely to avoid situation you are in now. So instead of declaring 100 separate variables you should use
String[] str = {"abc", "123", "aaa", ... , "zzz"};
and then access values via str[index] where index is value between 0 and size of your array -1, which in you case would be range 0 - 99.
If you would still would need to put all array elements to list you could use
List<String> elements = new ArrayList<>(Arrays.asList(str));
which would first
Arrays.asList(str)
create list backed up by str array (this means that if you do any changes to array it will be reflected in list, and vice-versa, changes done to list from this method would affect str array).
To avoid making list dependant on state of array we can create separate list which would copy elements from earlier list to its own array. We can simply do it by using constructor
new ArrayList<>(Arrays.asList(str));
or we can separate these steps more with
List<String> elements = new ArrayList<>();//empty list
elements.addAll(Arrays.asList(str));//copy all elements from one list to another
Yes. The way to use a loop is not to declare 100 string variables. Use one array instead.
String[] str = new String[101];
str[1] = "abc";
str[2] = "123";
str[3] = "aaa";
....
str[100] = "zzz";
(I made the indexes go from 1 to 100 to show how it corresponds to your original code, but it's more normal to go from 0 to 99 instead, and to initialize it with an array initializer as in #markspace's answer.)
The following creates the ArrayList on the specific String values you have:
ArrayList<String> list1 = new ArrayList<String>() {{addAll(Arrays.asList(new String[]{"99", "bb", "zz"}));}};
Or, if it's just some distinct values you want, use this for say - 10 of them:
ArrayList<String> list2 = new ArrayList<String>() {{for (int i=0; i<10; i++) add(""+System.currentTimeMillis());}};

Add multiple items to an already initialized arraylist in Java

My arraylist might be populated differently based on a user setting, so I've initialized it with
ArrayList<Integer> arList = new ArrayList<Integer>();
How can I add hundreds of integers without doing it one by one with arList.add(55);?
If you have another list that contains all the items you would like to add you can do arList.addAll(otherList). Alternatively, if you will always add the same elements to the list you could create a new list that is initialized to contain all your values and use the addAll() method, with something like
Integer[] otherList = new Integer[] {1, 2, 3, 4, 5};
arList.addAll(Arrays.asList(otherList));
or, if you don't want to create that unnecessary array:
arList.addAll(Arrays.asList(1, 2, 3, 4, 5));
Otherwise you will have to have some sort of loop that adds the values to the list individually.
What is the "source" of those integers? If it is something that you need to hard code in your source code, you may do
arList.addAll(Arrays.asList(1,1,2,3,5,8,13,21));
Collections.addAll is a varargs method which allows us to add any number of items to a collection in a single statement:
List<Integer> list = new ArrayList<>();
Collections.addAll(list, 1, 2, 3, 4, 5);
It can also be used to add array elements to a collection:
Integer[] arr = ...;
Collections.addAll(list, arr);
If you are looking to avoid multiple code lines to save space, maybe this syntax could be useful:
java.util.ArrayList lisFieldNames = new ArrayList() {
{
add("value1");
add("value2");
}
};
Removing new lines, you can show it compressed as:
java.util.ArrayList lisFieldNames = new ArrayList() {
{
add("value1"); add("value2"); (...);
}
};
Java 9+ now allows this:
List<Integer> arList = List.of(1,2,3,4,5);
The list will be immutable though.
In a Kotlin way;
val arList = ArrayList<String>()
arList.addAll(listOf(1,2,3,4,5))
If you needed to add a lot of integers it'd probably be easiest to use a for loop. For example, adding 28 days to a daysInFebruary array.
ArrayList<Integer> daysInFebruary = new ArrayList<>();
for(int i = 1; i <= 28; i++) {
daysInFebruary.add(i);
}
I believe scaevity's answer is incorrect. The proper way to initialize with multiple values would be this...
int[] otherList = {1,2,3,4,5};
So the full answer with the proper initialization would look like this
int[] otherList = {1,2,3,4,5};
arList.addAll(Arrays.asList(otherList));

Categories

Resources