ArrayList

import java.util.List;
import java.util.ArrayList;

public class CollectionTest {

	private static final String[] colors = { "Pink ", "Orange ", "Red ",
			"Green ", "Blue " };
	private static final String[] colorsToRemove = { "Red ", "Blue " };

	public CollectionTest() {

		List<String> list = new ArrayList<String>();

		// add elements from colors array to the list
		/* the following syntax "for (String S : c) {}"
		 * if like a foreach loop, and iterates over an array).
		 * In the below, each element of the array colors is
		 * assigned to String color, and then added the list
		 */
		for (String color : colors) {
			list.add(color);
		}

		System.out.println("Array list:");

		for (int count = 0; count < list.size(); count++) {
			System.out.printf("%s", list.get(count));
		}

		// remove elements
		for (String color : colorsToRemove) {
			list.remove(color);
		}

		System.out.println("\nArray list with colors removed:");

		for (int count = 0; count < list.size(); count++) {
			System.out.printf("%s", list.get(count));
		}

	}

	public static void main(String args[]) {
		new CollectionTest();
	}
}

Array list:
Pink Orange Red Green Blue
Array list with colors removed:
Pink Orange Green

Leave a Reply