Advertisement
AkanthaAnil

ArrayList conversion to Array

Apr 23rd, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.85 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. public class ArrayListToArray {
  5.  
  6.   public static void main(String[] args) {
  7.  
  8.     List<String> animals = new ArrayList<>();
  9.     animals.add("bird");
  10.     animals.add("dog");
  11.     animals.add("fish");
  12.     animals.add("cat");
  13.  
  14.    
  15.     String [] newAnimalsArray = animals.toArray(new String[0]);
  16.     System.out.println(newAnimalsArray.length);
  17.    
  18.     //Creating a new String array. If you specify a size of 0 for the parameter, Java will create a new array of the proper size for the return value.
  19.    
  20.     String [] newAnimalsArray = animals.toArray(new String[9]);
  21.     System.out.println(newAnimalsArray.length);
  22.    
  23.     //If you specify a length that the ArrayList already fits in (i.e. Array longer than its ArrayList) it will be returned. Otherwise, a new one will be created.
  24.    
  25.   }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement