0

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 ?

1
  • Fix your CAPS LOCK key. Commented Apr 24, 2021 at 5:49

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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-

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.