add to an array list code example

Example 1: ArrayList add(int index, E element) method in java

import java.util.ArrayList;
public class ArrayListAddMethodExample
{
   public static void main(String[] args)
   {
      // creating an empty ArrayList with initial capacity
      ArrayList<Integer> al = new ArrayList<Integer>(6);
      al.add(12);
      al.add(14);
      al.add(16);
      al.add(18);
      al.add(20);
      // adding element 15 at fourth position
      al.add(3, 15);
      for(Integer number : al)
      {
         System.out.println("Number: " + number);
      }
   }
}

Example 2: java arraylist add

//create ArrayList
ArrayList<String> arrayList = new ArrayList<String>();
//add item to ArrayList
arrayList.add("item");
//check if ArrayList contains item (returns boolean)
System.out.println(arrayList.contains("item"));
//remove item from ArrayList
arrayList.remove("item");

Example 3: how to get a user to add to an arraylist in java

public class chores {

	public static void main(String[] args) {
		
		Boolean close = false;
		
		ArrayList<String> name = new ArrayList();
		ArrayList<String> chores = new ArrayList();
		
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("Please enter '0'to exit");
		System.out.println("Please enter name: ");
		String answer = scanner.nextLine();
		if (answer == "0") {
			close = true;
			System.out.println("Program has been terminated.");
		}
		else {
			name.add(answer);
			
			do {
				
				System.out.println("Please enter chore: ");
				answer = scanner.nextLine();
				chores.add(answer);
				System.out.println("Please enter name: ");
				name.add(answer);
				
				
			}while(answer != "0");
        }
    }
}

Tags: