//handout #12 // *************************** // * Example of Interfaces // *************************** public interface IntList { public int size(); public int get(int index); public String toString(); public int indexOf(int value); public void add(int value); public void add(int index, int value); public void remove(int index); } public class ArrayIntList implements IntList { //usual implementation of ArrayIntList would go here } public class LinkedIntList implements IntList { //usual implementation of LinkedIntList would go here } // What's important to note here is that our variable is of // type IntList even though we make a new ArrayIntList(). // When posssible, it is considered much better style to use // variables of the interface type rather than the implementation // type. This is something you'll lose style points for on // exams and homeworks if you do it wrong. public static void main(String[] args) { IntList list1 = new ArrayIntList(); processList(list1); IntList list2 = new LinkedIntList(); processList(list2); } // *************************** // * Example of Iterators // *************************** import java.util.*; public class IteratorTest { public static void main(String[] args) { ArrayList list = new ArrayList(); list.add(1); list.add(3); list.add(2); list.add(3); //prints the values in the list //also removes values == 3 Iterator i = list.iterator(); while (i.hasNext()) { int n = i.next(); System.out.println(n); if (n == 3) { i.remove(); } } } } // Example of Maps // Stuart Reges // 10/29/05 // // This program prompts the user for the name of a file and then counts the // occurrences of words in the file (ignoring case). It then reports the // frequencies using a cutoff supplied by the user that limits the output // to just those words with a certain minimum frequency. import java.util.*; import java.io.*; public class WordCount { public static void main(String[] args) throws FileNotFoundException { // open the file Scanner console = new Scanner(System.in); System.out.print("What is the name of the text file? "); String fileName = console.nextLine(); Scanner input = new Scanner(new File(fileName)); input.useDelimiter("[^a-zA-Z']+"); // wordCounts occurrences SortedMap wordCounts = new TreeMap(); while (input.hasNext()) { String next = input.next().toLowerCase(); if (!wordCounts.containsKey(next)) { wordCounts.put(next, 1); } else { wordCounts.put(next, wordCounts.get(next) + 1); } } // get cutoff and report frequencies System.out.println("Total words = " + wordCounts.size()); System.out.print("Minimum number of occurrences for printing? "); int min = console.nextInt(); for (String word : wordCounts.keySet()) { int count = wordCounts.get(word); if (count >= min) System.out.println(count + "\t" + word); } } } //Other things to check out: // Iterators 608-611 // Interfaces 9.5 (but once again may be a bit confusing // Maps 11.3