//Example exploring generics // Beth Katz - March 2008 public class March17 { public static void main(String[] args) { doIntegers( ); doStrings( ); } /** * returns how many times target appears in list */ public static int howMany(Node list, Comparable target) { int count = 0; for (Node p = list; p != null; p = p.getLink( )) { if (target.compareTo(p.getData( )) == 0) { count++; } } return count; } /** * prints the list's contents with each node's data followed by a space */ public static void printList(Node list) { for (Node p = list; p != null; p = p.getLink( )) { System.out.print(p.getData( ) + " "); } System.out.println( ); } /** * an example of using Integers (not int - the wrapper class Integers) * creates a list of Integers and counts how many 42s are in it */ public static void doIntegers( ) { Node intList = null; intList = new Node(42, intList); intList = new Node(17, intList); intList = new Node(5, intList); intList = new Node(42, intList); intList = new Node(5, intList); intList = new Node(42, intList); printList(intList); System.out.println("Number of 42s: " + howMany(intList, 42)); } /** * an example of using Strings * creates a list of names and counts how many 42s are in it */ public static void doStrings( ) { Node sList = null; sList = new Node("left", sList); sList = new Node("foot", sList); sList = new Node("left", sList); sList = new Node("foot", sList); sList = new Node("right", sList); sList = new Node("foot", sList); sList = new Node("right", sList); printList(sList); System.out.println("Number of 'foot's: " + howMany(sList, "foot")); } }