正在加载图片...
Chapter 10: Detecting Types put()和get()是关联性数组的两个基本方法,但是考虑到程序的输 出,我们还覆写了 tostring()方法,让它把键和值全都打印出来。为 了看看它是不是能正常工作,main()先是往 AssociativeArray里填 了一组成对的字符串,然后把它打印了出来,最有再用get()提取了 个值 现在所有工具都已经准备好了,我们可以用 instanceof来数Pet了: //: c10: Petcount java // Using instanceof package cl0; import com. bruceeckel. simpletest* import java.util.*i public class Petcount private static Test monitor private static Random rand neg Random o)i static String[] typenames Rodent","Gerbil","Hamster " / Exceptions thrown to console public static void main(String[ args)i Object[] pets new object[15] Class[] petT Class. forName("c10 Dog Class forName(" c10. Pug") 0. Cat") Class. forName("c10 Rodent ") Class. forName("cl0 Gerbil" ), lass. forName("c10 Hamster") f petTypes [rand. nextInt(petTypes. length)] new Instance( y catch(InstantiationException e) System. out. println("Cannot instantiate")i System. exit(l)i catch(IllegalAccessException e) System. out. println("Cannot access") ystem. exit (1) 1 catch(ClassNot FoundException e)I System. out. println("Cannot find class") AssociativeArray map new AssociativeArray(typenames length for(int map.put(typenames [i], new Counter())i for(int i =0; i< pets. length; i++)i Object if(o instanceof Pet) ((Counter)map. get("Pet")).i++ f if(o instanceof Pug) 第10页共17页 www.wgqqh.com/shhgs/tij.htmlChapter 10: Detecting Types www.wgqqh.com/shhgs/tij.html email:shhgs@sohu.com 第 10 页 共 17 页 put( )和 get( )是关联性数组的两个基本方法,但是考虑到程序的输 出,我们还覆写了 toString( )方法,让它把键和值全都打印出来。为 了看看它是不是能正常工作,main( )先是往 AssociativeArray 里填 了一组成对的字符串,然后把它打印了出来,最有再用 get( )提取了一 个值。 现在所有工具都已经准备好了,我们可以用 instanceof 来数 Pet 了: //: c10:PetCount.java // Using instanceof. package c10; import com.bruceeckel.simpletest.*; import java.util.*; public class PetCount { private static Test monitor = new Test(); private static Random rand = new Random(); static String[] typenames = { "Pet", "Dog", "Pug", "Cat", "Rodent", "Gerbil", "Hamster", }; // Exceptions thrown to console: public static void main(String[] args) { Object[] pets = new Object[15]; try { Class[] petTypes = { Class.forName("c10.Dog"), Class.forName("c10.Pug"), Class.forName("c10.Cat"), Class.forName("c10.Rodent"), Class.forName("c10.Gerbil"), Class.forName("c10.Hamster"), }; for(int i = 0; i < pets.length; i++) pets[i] = petTypes[rand.nextInt(petTypes.length)] .newInstance(); } catch(InstantiationException e) { System.out.println("Cannot instantiate"); System.exit(1); } catch(IllegalAccessException e) { System.out.println("Cannot access"); System.exit(1); } catch(ClassNotFoundException e) { System.out.println("Cannot find class"); System.exit(1); } AssociativeArray map = new AssociativeArray(typenames.length); for(int i = 0; i < typenames.length; i++) map.put(typenames[i], new Counter()); for(int i = 0; i < pets.length; i++) { Object o = pets[i]; if(o instanceof Pet) ((Counter)map.get("Pet")).i++; if(o instanceof Dog) ((Counter)map.get("Dog")).i++; if(o instanceof Pug)
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有