Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From Arraylist to Array

Tags:

java

arraylist

I want to know if it is safe/advisable to convert from ArrayList to Array? I have a text file with each line a string:

1236 1233 4566 4568 .... 

I want to read them into array list and then i convert it to Array. Is it advisable/legal to do that?

thanks

like image 387
Eddy Freeman Avatar asked Nov 01 '11 15:11

Eddy Freeman


People also ask

Is ArrayList better than array?

An array is faster and that is because ArrayList uses a fixed amount of array. However when you add an element to the ArrayList and it overflows. It creates a new Array and copies every element from the old one to the new one.

What is toArray () in Java?

The Java ArrayList toArray() method converts an arraylist into an array and returns it. The syntax of the toArray() method is: arraylist.toArray(T[] arr) Here, arraylist is an object of the ArrayList class.


2 Answers

Yes it is safe to convert an ArrayList to an Array. Whether it is a good idea depends on your intended use. Do you need the operations that ArrayList provides? If so, keep it an ArrayList. Else convert away!

ArrayList<Integer> foo = new ArrayList<Integer>(); foo.add(1); foo.add(1); foo.add(2); foo.add(3); foo.add(5); Integer[] bar = foo.toArray(new Integer[foo.size()]); System.out.println("bar.length = " + bar.length); 

outputs

bar.length = 5 
like image 101
ObscureRobot Avatar answered Sep 30 '22 12:09

ObscureRobot


This is the best way (IMHO).

List<String> myArrayList = new ArrayList<String>(); //..... String[] myArray = myArrayList.toArray(new String[myArrayList.size()]); 

This code works also:

String[] myArray = myArrayList.toArray(new String[0]); 

But it less effective: the string array is created twice: first time zero-length array is created, then the real-size array is created, filled and returned. So, if since you know the needed size (from list.size()) you should create array that is big enough to put all elements. In this case it is not re-allocated.

like image 42
AlexR Avatar answered Sep 30 '22 11:09

AlexR