package examples; import java.util.*; /** * CS401 Example 32d * * Changes ex29.java to use the new Generic syntax. This examples shows the use * of multiple Generic types in the same data structure. * * @author PJ Dillon */ public class ex32d { public static void main(String[] args) { // Cities and Teams we'll store in our Map String[] cities = {"Buffalo", "Cleveland", "Pittsburgh", "New York", "Boston", "Chicago", "Atlanta", "St. Louis"}; String[][] teams = {{"Bills", "Sabres"}, {"Indians", "Cavs", "Browns"}, {"Pirates", "Steelers", "Peguins"}, {"Yankees", "Mets", "Giants", "Jets", "Knicks", "Islanders"}, {"Red Sox", "Patriots", "Celtics", "Bruins"}, {"White Sox", "Cubs", "Bears", "Bulls", "Black Hawks"}, {"Braves", "Falcons", "Hawks"}, {"Cardinals"}}; /* * The declaration here states that our key type must be a String, which * will index a Collection of Strings. The compiler will then ensure this is * upheld. */ Map> map = new HashMap>(); Collection c; for(int i = 0; i < cities.length; i++) { c = new TreeSet(); for(int j = 0; j < teams[i].length; j++) c.add(teams[i][j]); map.put(cities[i], c); } //loop asking the user for the name of a city Scanner in = new Scanner(System.in); System.out.print("Enter city name ('done' to exit): "); String city = in.nextLine(); while(!city.equals("done")) { /* * We now know for sure what type of Object will be returned from the Map; * Prior to this, we assumed it was a Collection and cast it as such. Now, * no assumption is necessary. */ Collection team = map.get(city); if(team == null) System.out.println("\nNo info for " + city + '\n'); else { System.out.println("\nTeams in " + city + ": "); for(String o : team) System.out.print(o + ", "); System.out.println('\n'); } System.out.print("Enter city name ('done' to exit): "); city = in.nextLine(); } } }