Guest User

Untitled

a guest
Jan 21st, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. import java.util.ArrayList;
  2.  
  3. public class Main {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. ArrayList<String> strings = new ArrayList<>(4); //Can add 4 elements without reallocation
  8. System.out.println(strings.size()); //Like .length()
  9. strings.add("Vehicle"); //Add elements
  10. strings.add("Dolphin");
  11. strings.add("Jordan Peterson");
  12. strings.add("Booty");
  13. strings.add(1, "New Dolphin"); //Choose WHERE to put the elements
  14. System.out.println(strings.size());
  15.  
  16. //Print out the contents of the array list
  17. System.out.println(strings);
  18.  
  19. //Remove elements too
  20. strings.remove("Jordan Peterson"); //Remove it by its value/object
  21. strings.remove(3); //Remove by index
  22. System.out.println(strings);
  23.  
  24. //Set capacity equal to the number of elements currently in the arraylist
  25. strings.trimToSize();
  26.  
  27. //Convert an arraylist to a regular array
  28. ArrayList<Double> doubleAL = new ArrayList<>();
  29. doubleAL.add(2.4);
  30. doubleAL.add(4.0);
  31. doubleAL.add(213.3);
  32. //Double array to store our arraylist
  33. Double doubles[] = new Double[doubleAL.size()]; //You have to specify the length for arrays without an initial value
  34. doubles = doubleAL.toArray(doubles);
  35. for (int i = 0;i < doubles.length;i++){
  36. System.out.println(doubles[i]);
  37. }
  38.  
  39. }
  40. }
Add Comment
Please, Sign In to add comment