CIS191-S09/Slides and Notes/March 23 - 27

From MCIS Wiki

Jump to: navigation, search

ArrayList examples

package arraylistdemos;
import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        ArrayList<String> strings = new ArrayList<String>();
        strings.add("A");
        strings.add("B");
        strings.add("C");
        System.out.println("The ArrayList<String>: " + strings);
        System.out.println("Length = " + strings.size());
        System.out.println("Using iteration:");
        for (String s : strings) System.out.println("  " + s);
        System.out.println("String at strings[0] = " + strings.get(0));
        strings.add(0, "New");
        System.out.println("After adding New at position 0: " + strings);
        strings.remove(1);
        System.out.println("After a remove at 1: " + strings);
        // Write code to remove the last element then print the strings
        strings.remove(strings.size()-1);
        System.out.println("Removing the last element: " + strings);
        // Write code to make a new ArrayList which is a copy of strings
        ArrayList<String> strings1 = new ArrayList<String>();
        for (String s : strings) {
            strings1.add(s); }
        System.out.println("Copying the array: " + strings1);
        // Write code to make a new ArrayList which is a reversed copy of strings
        ArrayList<String> strings2 = new ArrayList<String>();
        for (String s : strings) {
            strings2.add(0, s); }
        System.out.println("Reversing the array: " + strings2);
        // Write a method to search through an ArrayList and look for a specific value
        System.out.println("String A in " + strings + " ? " + findString("A", strings));
        System.out.println("String B in " + strings + " ? " + findString("B", strings));

    }
    // Ignore the "static" thing!
    static boolean findString(String s, ArrayList<String> a) {
        for (String s1 : a)
            if (s.equals(s1)) return true;
        return false;
    }
}
Personal tools