Change size of an array by an arraylist - java

One of the main Charucteristic of the Array is immutability(Size of the array cant be changed) but while i was practicing i found myself in this case :
We have an Array with specific size
String[] strArr = new String[1];
And ArrayList with Objects
ArrayList<String> list = new ArrayList<>();
list.add("Alex");
list.add("Ali");
list.add("Alll");
So when we try to convert the list to an array and assign it to strArr , like this
strArr = list.toArray(strArr);
for(String str : strArr ) {
System.out.println(str);
}
It works without a problem even if the size of the array doesnt equal the size of the list
So I JUST WANT TO KNOW HOW THIS IS POSSIBLE , WHEN THE SIZE OF THE ARRAY CANT BE CHANGED ?

New array allocated
strArray first references to a String array of size 1, when you do strArr = list.toArray(strArr);, you change the reference of strArray to a different array. So you are not changing the array size, you are only changing to which array now strArrays refers to.
Possibly you assume that list.toArral(strArr) modifies strArr but that's not the case, as you can read at the java documentation. It reads:
"If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list"
The important section for your case, is where the documentation says: "Otherwise, a new array is allocated", so, no array resize is done.

You can use
strArr = list.subList(0, strArr.length).toArray(strArr);
Basicaly, the List#subList(fromIndex, toIndex) creates a new List with the elements starting in the fromIndex up to toIndex (self-explaintory)
You can read more about in https://docs.oracle.com/javase/8/docs/api/java/util/List.html#subList-int-int-

It changes the reference to a new object. You can check this by calling: System.out.println(strAttr) immediately after you first assign the variable and then again after you call strArr = list.toArray(strArr);

Related

How to append data into a String list in Java

I am new to Java and Here is my code.
String[][] datas={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
String[] onedata={"j","k","l"};
the thing I want to do here is that, I want to append the onedata into datas at last index value.
Please help let me know that how can I do this.
You can use an ArrayList because their sizes are mutable. For example:
String[][] datas={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
List<String[]> datasList = new ArrayList<>(Arrays.asList(datas));
String[] onedata = {"j","k","l"};
datasList.add(onedata);
datas = datasList.toArray(new String[datasList.size()][]);
The things you are dealing with are arrays (String[]) and multidimensional arrays (String[][]) in Java, not lists. Their length is fixed. Therefore to append a new item to an array in such way that the length increases (so not by replacing the last item in the current array) you would need to create a new array with length n+1, assign the old values to the first n indices and then the new value to the index n+1.

How can add an element to an array?

I wrote this code with a String array:
public static String[] prgmNameList = {"bbbbb", "aaaaa"};
My question is now, how can I add a new item to that array like this:
prgmNameList.add("cccc");
prgmNameList is an array. The size of an array object cannot be changed once it has been created. If you want a variable size container, use collections. For example, use an ArrayList :
List<String> prgmNameList = new ArrayList<String>(3);
prgmNameList.add("bbbb");
That said, if you insist on using an array, you will need to copy your initial array into a new array for each new element that you want to add to the array which can be expensive. See System#arrayCopy for more details. In fact, the ArrayList class internally uses an array that is expanded once it is full using System.arrayCopy so why reinvent the wheel? Just use an ArrayList
On simpler terms, note these following points:
Array size is always fixed.(In your example you fixed the array size to 2 by adding 2 elements)
Arrays operate based on index starting from '0' zero, like - prgmNameList[0] will return 1st element added in the array
Array size cannot be changed at any point of time. If you need size to be variable, choose one of List implementations
ArrayList is the best option for your need that can define itself as an 'Array that can shrink or grow'
Sample code:
public static List<String> prgmNameList= new ArrayList<String>();
prgmNameList.add("bbb");
prgmNameList.add("bbb");
prgmNameList.add("ccc");
prgmNameList.remove("bbb"); //Removes by object resolved by equals() method
prgmNameList.remove(2); //Removes by index
You have created an Array which can not grow as it's fixed in size.
You need to create a list in order to add new elements as shown below.
List<String> prgmNameList = new ArrayList<String>();
prgmNameList.add("aaaa");
prgmNameList.add("bbbb");
prgmNameList.add("cccc");
You have to use ArrayList like that
ArrayList<String> al = new ArrayList<>();
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
if you want to use array as you did you have to know the number of elements that you want to add
String[] myList = new String[10];
and then
myList[4]="AA"
--
this is not possible to add to myList.
I explain you how ArrayList works and then you will understand.
ArrayList is an class that contains Array from objects. every time you add it check if it have place to store the data in the array if not it creates new array bigger and store the data.
So ArrayList this is the solution (or any other list)
if you want to add to myList you will have to implement arratList..
The method you are looking for is defined for a Collection, but you are using an array with an array initializer.
I suggest switching to the List:
public static List<String> prgmNameList= new ArrayList<>(Arrays.asList("bbbbb","aaaaa"))
Then you can call add on it because now it is a list.
Btw.: Try to prevent having mutable variables in static variables.

How to get an element from a String Array, if the String array itself is an element of an ArrayList?

Let me give you an example;
String[] one = {"one", "two"};
String[] two = {"bob", "lol", "hi"};
List<String[]> list = new ArrayList<String[]>();
list.add(one);
list.add(two);
Now, I want to get the 2nd string array (which is 'two') in list. I do this by:
list.get(2);
But, say if I wanted to get the 2nd element in the two String array in List ( Basically I want to get the string "lol" from list->two->lol).
Is this how you do it:
list.get(2).get(2)
Indices in Java (and in most programming languages) starts with 0, so if you want to access to the second element you must use the index 1:
list.get(0)[1];
Note that
list.get(0)
will return the first String[] array, and to access to an element of an array you have to use the syntax:
someArray[index]
Array starts with index 0. so you have to use list.get(i)[1]

Adding values to already initialized object array in Java?

I'm developing for the Android platform and, to simplify the question, I'm using pseudo-names for the entities.
I have an object array stuff[] of the class StuffClass[].
StuffClass stuff[]={
new StuffClass(Argument, argument, argument),
new StuffClass(argument, argument, argument)
};
I have an activity returning a result of three arguments that I want to then use to add a new object to stuff[]. I've done so as follows:
stuff[stuff.length]=new StuffClass(argument, argument, argument);
and I get ArrayOutOfBounds (Figured that would happen).
So how might I go about creating a new object in the stuff[] array?
Arrays are static you can't change size without creating a new one before. Instead of that you can use a dynamic data structure such as an ArrayList
Example:
List<MyType> objects = new ArrayList<>();
objects.add(new MyType());
Here you forget about array size.
Array in Java is little bit special, it's length is fixed when it's initialized, you can not extend it later on.
What you can do is to create a new array, and use System.arraycopy to generate a new array, here's the sample code:
String[] arr1 = new String[]{"a", "b"};
String[] arr2 = new String[3];
System.arraycopy(arr1, 0, arr2, 0, 2);
arr2[2] = "c";
You cannot increase the size of an existing array. Once it's created, the size of the array is fixed.
You will need to create another bigger array and copy the items from the old array to the new array.
A better alternative is to use an ArrayList. When you add items to an ArrayList, the capacity will grow behind the scenes if needed; you don't have to worry about increasing the size.
you can use the ArrayList to do this
arraylist.add(object);
in java arrays are fixed length. you need to initialise them with the desired length.
Consider using a Collection such as ArrayList which will handle everything for you.
List<StuffClass> myList = new ArrayList<>();
myList.add(...);
Lists support similar behaviour to arrays ie:
myList.set(i, elem);
myArray[i] = elem;
elem = myList.get(i);
elem = myArray[i];
len = myList.size();
len = myArray.length;
You can then convert the list to an array.
StuffClass[] myArray = myList.toArray(new StuffClass[myList.size()]);
If you don't want to use lists consider using System.arrayCopy to create a new array with more elements.
read here for a good description.

java - Convert String ArrayList to String Array with bigger size

I am trying to convert Array list to String array but getting an exception. Can somebody please help me.
Size of ArrayList: 1
Size of String Array: 2
I am using the following code:
String[] StringArray ={};
StringArray = ArrayList.toArray(new String[ArrayList.size()]);
So, the length of StringArray now is 1. But it should be 2. My problem is how can i convert arraylist to StringArray if String Array size is more than the ArrayList.
How can i do that? Please guys help me.
If you want to convert ArrayList to a bigger String array, use toArray() and pass the array you want to fill as parameter. If the array size is more than needed, the rest of the elements will be null. If the array is smaller - a new array will be returned with size as list.size.
All taken from javadoc
ArrayList<String> list = new ArrayList<>();
list.add("abc");
String[] StringArray = new String[2];
StringArray = list.toArray(StringArray);
In that case, even though the list size is 1, StringArray is of size 2, adding null values at the end of the array.
String[] arr = new String[list.size()];
arr = list.toArray(arr);
Try to do it like in this tutorial: http://viralpatel.net/blogs/convert-arraylist-to-arrays-in-java/
The size of array defined before .toArray method has no effect on result. After calling .toArray, old array is destroyed by JVM.
If we pass an array as argument to method toArray then it populates that with the items of list else it returns an array of Object. We can pass an array of size larger than the list as argument to get an array of greater size. The following example explains it:
public static void main(String[] args) throws FileNotFoundException {
List<String> list = new ArrayList<>();
list.add("One");
System.out.println("list Size: " + list.size());
//If we pass an array as argument it will be filled with items from list and then returned. Here array size is (list.size +2 )
String[] stringArray = list.toArray(new String[2]);
System.out.println("stringArray Size: " + stringArray.length);
//If we do not pass an array as argument we get Object[] of same size
Object[] objects = list.toArray();
System.out.println("objects Size: " + objects.length);
// Java 8 has option of streams to get same size array
String[] stringArrayUsingStream = list.stream().toArray(String[]::new);
System.out.println("stringArrayUsingStream Size: " + stringArrayUsingStream.length);
}
As shown above we have an option of using streams also in Java 8. The output is:
list Size: 1
stringArray Size: 2
objects Size: 1
stringArrayUsingStream Size: 1

Categories