Array List
Using array lists to add, remove get and more.
import java.util.ArrayList; // importing the ArrayList Class
class ShapesClass {
public static void main( String args[] ) {
ArrayList<String> shapes = new ArrayList<String>(); //create an ArrayList with string data type
//Add a bunch of shapes to start off.
shapes.add("square");
shapes.add("triangle");
shapes.add("hexagon");
shapes.add("rhombus");
shapes.add("octagon");
shapes.add("rectangle");
shapes.add("pentagon");
//Print all the shapes
System.out.println("Shapes in ArrayList:");
System.out.println(shapes); // prints all elements of ArrayList shapes
System.out.println();
//Get element at index 4
System.out.println("Element at index 4:");
System.out.println(shapes.get(4)); // print element at index 4
System.out.println();
//Remove elements at 3 and 5 but have to remove 3 and 4 since removing 3 takes 5 down by 1.
System.out.println("Remove elements at index 3 and 5:");
shapes.remove(3); // removing element at index 3
shapes.remove(4); // removing element at index 5 since removing 3 moves the index down 1.
System.out.println(shapes); // prints all elements of ArrayList shapes
System.out.println();
//Set index 4 as "circle"
System.out.println("Set index 4 as circle:");
shapes.set(4,"circle"); // replaces element at index 4 with circle
System.out.println(shapes); // prints all elements of ArrayList shapes
System.out.println();
//Get the total number of elements in ArrayList
System.out.println("Number of elements in ArrayList:");
System.out.println(shapes.size()); // prints the number of elements in the ArrayList
System.out.println();
//Add a second hexagon and get the index of the first one
System.out.println("Add hexagon:");
shapes.add("hexagon"); // Adds hexagon
System.out.println(shapes); // prints all elements of ArrayList shapes
System.out.println("Get 1st hexagon index:");
System.out.println(shapes.indexOf("hexagon"));
System.out.println();
//Clear the ArrayList
System.out.println("Clear ArrayList:");
shapes.clear(); // removes all elements in the ArrayList
System.out.println(shapes); // prints all elements of ArrayList shapes
System.out.println();
}
}
ShapesClass.main(null);