简体   繁体   中英

[JAVA]I converted a LinkedList of type Integer into an Array.How to determine the size of the array after the conversion

I created a LinkedList and added the below elements to it.

List<Integer> integers = new LinkedList<>();
integers.add(0);
integers.add(45);
integers.add(95);
integers.add(5);
integers.add(12);

Integer[] arr = integers.toArray(new Integer[3]);
    System.out.println(arr.length);
for(int c:arr)  {
  System.out.println(c);
}

The length of the array is printed as 5,when I have restricted the length of the array to 3.All the Elements are displayed in the output.

And then if I try adding 6th element to the array it gives

java.lang.ArrayIndexOutOfBoundsException: 6

How is the Length of the Array being determined here? Why the anomalous behaviour of Array?

To be expected, just read the javadoc for List.toArray() :

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. 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 .

Thus: when you use this method it will figure: the list has 5 elements, not 3. So it creates an array with room for 5 items, and thus arr.lenght is 5.

And of course, array indexes go from 0 to 4, so when you go for arr[5] you are "one off" - out of the boundaries of the array.

That is all there is to this.

That line:

Integer[] arr = integer.toArray(new Integer[3]);

can be even replaced with

Integer[] arr = integer.toArray(new Integer[0]);

you could think that array will have length of... 0 ?

Yet the argument Integer[0] s only needed for a type recognition for the array you are converting to.

Therefore, you will get the same result: integer list converted to an array of integer list size, which is 5 ,

And since its length is 5 , you can access only indexes of 0,1,2,3,4 , so 6th is clearly out of bounds of the array.

如果您只想在新数组中包含前三个元素,则可以执行以下操作:

Integer[] arr2 = integer.stream().limit(3).toArray(Integer[]::new);

Let's split an answer into the 2 topics

List.toArray behavior

This is not something specific to a LinkedList, but to all List collections in Java. According to Java Doc for the method <T> T[] toArray(T[] a) of both List interface and LinkedList implementation, the behavior is following:

  1. If the list fits in the specified array a , it is returned therein

  2. If the list does not fit in passed array a , the newly-allocated array of required size is returned of the same runtime type as a

General Examples using java.util.Arrays utility class:

List<Integer> list = Arrays.asList(0,45,95,5,12); //creates a list of 5 elements

Integer[] enoughCapacity = new Integer[list.size()]; // the same as new Integer[5]
Integer[] exported = list.toArray(enoughCapacity);
System.out.println(enoughCapacity == exported); //prints 'true' because both references initial and exported point to the same array

Integer[] smallerCapacity = new Integer[3];
Integer[] anotherExported = list.toArray(smallerCapacity); // here only runtime type of smallerCapacity array will be used by toArray
System.out.println(smallerCapacity == anotherExported); //prints 'false' because anotherExported is newly-allocated array of list size 
System.out.println(smallerCapacity.length); // prints '3' thus smallerCapacity points to a different array and remains unchanged
System.out.println(anotherExported.length); // prints '6'

Adding extra element to an array

Array, once allocated, cannot have more elements than its length. That's why you're getting ArrayIndexOutOfBoundsException when trying to add 6-th element to the array of size 5 It is still possible to expand array capacity by using

Integer[] array = new Integer[5];
array = Arrays.copyOf(array,6); //this "expands" capacity to 6
array[5] = 42; // remember, indexing starts from 0 and 6-th element has index of 5
System.out.println(array.length); //prints '6'

but please note, that Arrays.copyOf ( Java Doc ) actually is a shortcut for allocating brand new array and copying content of old array into the new one. Which seems to be quite expensive comparing to working with corresponding Java Collections which are well designed for adding new elements, eg LinkedList

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM