• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java.util.ArrayList.toArray(T[]) method question  RSS feed

 
Ioanna Katsanou
Ranch Hand
Posts: 131
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a confusion about the toArray() method.
I understand that the toArray is a bridge between array-based and collection-based.
it converts an ArrayList to an array[].

I can understand the method Java.util.ArrayList.toArray(), but I cannot seem to understand the other method signature Java.util.ArrayList.toArray(T[]).



In this example, are list3 and list2 the same??
If list2 was smaller than the arrlist.size(),
then in this example it list2 = null and a list3 has the same content with arrlist and a new EXTRA array is created?
for example:



and what about this case? :




 
Junilu Lacar
Sheriff
Posts: 11493
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The differences are explained in detail in the API JavaDocs. http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#toArray--

Please review that carefully. If you have further doubts, you can come back and ask more specific questions.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ioanna Katsanou wrote:. . .. . .
What would be wrong with this
System.out.println(arrList);
I suggest you revise your teaching about what a newly‑created array contains. You can verify the details of the arrays with
System.out.println(myArray);
...but arrays don't override the Object#toString() method; this other technique will be easier to understand:-
System.out.println(Arrays.toString(myArray));
Why are you setting the sizes of the arrays to the same as the List? Does it say anything in the documentation about the size of the array passed as an argument to the toArray method? Try this:-
Integer[] numbersArray = numbersList.toArray(new Integer[]{});
Work out the contents of the array passed to toArray in that last line.
Why are you calling the arrays list2/list3? Those names will confuse you. Always put the [] on the left of the array's name. Not
Integer array1[] ...
but
Integer[] array1 ...
Don't declare your list as ArrayList, but as List:-
List<Integer> numbersList = new ArrayList<>();
The toArray method is in the List interface.
Your other questions are all about different values being assigned to variables. Do you still need help with them?
 
Ioanna Katsanou
Ranch Hand
Posts: 131
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok I understood it thank you )
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!