Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- public class Main {
- public static void main(String[] args) {
- ArrayList<String> strings = new ArrayList<>(4); //Can add 4 elements without reallocation
- System.out.println(strings.size()); //Like .length()
- strings.add("Vehicle"); //Add elements
- strings.add("Dolphin");
- strings.add("Jordan Peterson");
- strings.add("Booty");
- strings.add(1, "New Dolphin"); //Choose WHERE to put the elements
- System.out.println(strings.size());
- //Print out the contents of the array list
- System.out.println(strings);
- //Remove elements too
- strings.remove("Jordan Peterson"); //Remove it by its value/object
- strings.remove(3); //Remove by index
- System.out.println(strings);
- //Set capacity equal to the number of elements currently in the arraylist
- strings.trimToSize();
- //Convert an arraylist to a regular array
- ArrayList<Double> doubleAL = new ArrayList<>();
- doubleAL.add(2.4);
- doubleAL.add(4.0);
- doubleAL.add(213.3);
- //Double array to store our arraylist
- Double doubles[] = new Double[doubleAL.size()]; //You have to specify the length for arrays without an initial value
- doubles = doubleAL.toArray(doubles);
- for (int i = 0;i < doubles.length;i++){
- System.out.println(doubles[i]);
- }
- }
- }
Add Comment
Please, Sign In to add comment