ListExamples

import java.util.*; // needed for ArrayList, Scanner

public class ListExamples

{

    public static void readList()

    {

        ArrayList<Integer> myList = new ArrayList<Integer>();

        

        Scanner sc = new Scanner (System.in);

        System.out.print("Enter a #, or -1 to stop: ");

        int input = sc.nextInt();

        sc.nextLine(); // consume extraneous newline

        

        while (input != -1)

        {

            myList.add(0, input); // inserts input at position 0

            System.out.println("myList now has " + myList.size() + " item(s).");

            

            System.out.println("\nList contents:");

            

            // OLD WAY OF PRINTING A LIST

            for (int i = 0; i < myList.size(); i++)

            {

                int foo = myList.get(i);

                System.out.print(foo + " ");

            }

            

            System.out.println();

            

            

            

            System.out.print("Enter a #, or -1 to stop: ");

            input = sc.nextInt();

            sc.nextLine(); // consume extraneous newline

        }

        

        System.out.println("Removing value at position 2...");

        myList.remove(2);

        

        // NEW WAY TO PRINT A LIST

        for (int val : myList) // For each int "val" in the list...

        {

            System.out.print(val + " "); // print "val"

        }

        

        System.out.println();

        

        System.out.println("Changing element at position 1 to 35...");

        myList.set(1, 35);

        

        for (int val : myList) // For each int "val" in the list...

        {

            System.out.print(val + " "); // print "val"

        }

        

        System.out.println();

    }

}

This page was last modified on 8/25/09