ArrayList
import java.util.Arrays;
import java.util.ArrayList;
public class ArrayVArrayList {
public static void main(String[] args){
//Declaring an Array
// Also can do: String[] scrumArray = new String[4]; //initializes string array and must give size
// ^^ all 4 elements are null until they are set
String[] scrumArray = {"Calissa", "Evan", "Kian", "Samuel"}; //initializes values right away, size is implied
//Declaring an ArrayList
// Also can do: ArrayList<String> scrumArrayList = new ArrayList<>(); //instantiate arraylist, must declare datatype, uses diamond (<>) operator
ArrayList<String> scrumArrayList = new ArrayList<>(Arrays.asList("Calissa", "Evan", "Kian", "Samuel")); //passes .asList method (values you want to have in your arrayList)
//Getting value from Array
System.out.println(scrumArray[1]);
//Getting value from Array
System.out.println(scrumArrayList.get(1));
//Getting length from Array
System.out.println(scrumArray.length); //field on array
//Getting length from ArrayList
System.out.println(scrumArrayList.size()); //size is method call
//Adding element to end of ArrayList
scrumArrayList.add("John"); //calls add method, pass element you want to add
System.out.println(scrumArrayList.get(4));
//Change element in Array
scrumArray[1] = "Hassan";
System.out.println(scrumArray[1]);
//Change element in ArrayList
scrumArrayList.set(1, "Hassan");
System.out.println(scrumArrayList.get(1));
//Remove element in ArrayList
/*
* Note: Can also do scrumArrayList.remove("ObjectName");
*/
scrumArrayList.remove(1);
System.out.println(scrumArrayList.get(1));
//Print Array
System.out.println(scrumArray); //gives memory address
//^^In order to print array you have to do a for loop and iterate over all elements
System.out.println(scrumArrayList); //implemented two string method so it prints out nicely
}
}
ArrayVArrayList.main(null);