【ThinkingInJava】29、对类进行计数

本文介绍了如何使用Java中的类型信息来创建不同种类的宠物对象,并通过实例代码演示了PetCreator类的实现,以及如何利用它来生成随机的宠物数组和集合。重点展示了通过类型信息动态创建对象的灵活性和便利性。
<pre name="code" class="java">//: typeinfo/pets/PetCreator.java
// Creates random sequences of Pets.
package Lesson14TypeInformation.pets;
import java.util.*;

public abstract class PetCreator {
  private Random rand = new Random(47);
  // The List of the different types of Pet to create:
  public abstract List<Class<? extends Pet>> types();
  public Pet randomPet() { // Create one random Pet
    int n = rand.nextInt(types().size());
    try {
      return types().get(n).newInstance();
    } catch(InstantiationException e) {
      throw new RuntimeException(e);
    } catch(IllegalAccessException e) {
      throw new RuntimeException(e);
    }
  }	
  public Pet[] createArray(int size) {
    Pet[] result = new Pet[size];
    for(int i = 0; i < size; i++)
      result[i] = randomPet();
    return result;
  }
  public ArrayList<Pet> arrayList(int size) {
    ArrayList<Pet> result = new ArrayList<Pet>();
    Collections.addAll(result, createArray(size));
    return result;
  }
} ///:~




//: typeinfo/pets/ForNameCreator.java
package Lesson14TypeInformation.pets;
import java.util.*;

public class ForNameCreator extends PetCreator {
  private static List<Class<? extends Pet>> types =
    new ArrayList<Class<? extends Pet>>();
  // Types that you want to be randomly created:
  private static String[] typeNames = {
    "Lesson14TypeInformation.pets.Mutt",
    "Lesson14TypeInformation.pets.Pug",
    "Lesson14TypeInformation.pets.EgyptianMau",
    "Lesson14TypeInformation.pets.Manx",
    "Lesson14TypeInformation.pets.Cymric",
    "Lesson14TypeInformation.pets.Rat",
    "Lesson14TypeInformation.pets.Mouse",
    "Lesson14TypeInformation.pets.Hamster"
  };	
  @SuppressWarnings("unchecked")
  private static void loader() {
    try {
      for(String name : typeNames)
        types.add(
          (Class<? extends Pet>)Class.forName(name));
    } catch(ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
  }
  static { loader(); }
  public List<Class<? extends Pet>> types() {return types;}
} ///:~


/**
* 书本:《Thinking In Java》
* 功能:为了对pet进行计数,我们做一个能跟踪各种不同类型的Pet的数量的工具,用map
* 文件:PetCount.java
* 时间:2015年4月13日17:25:39
* 作者:cutter_point
*/
package Lesson14TypeInformation;

import java.util.HashMap;

import Lesson14TypeInformation.pets.*;
import static net.mindview.util.Print.*;

public class PetCount 
{
	static class PetCounter extends HashMap<String, Integer>
	{
		public void count(String type)	//添加一个pet
		{
			Integer quantity = this.get(type);
			
			if(quantity == null)	//如果没有那么就变为1
				this.put(type, 1);
			else		//如果有,那么就在基础上加一个
				this.put(type, quantity+1);
		}
	}
	
	public static void countPets(PetCreator creator)
	{
		PetCounter counter = new PetCounter();
		for(Pet pet : creator.createArray(20))
		{
			printnb(pet.getClass().getSimpleName() + " ");
			
			if(pet instanceof Pet)		//判断是不是这个类
				counter.count("Pet");
			if(pet instanceof Dog)
				counter.count("Dog");
			if(pet instanceof Mutt)
				counter.count("Mutt");
			if(pet instanceof Pug)
				counter.count("Pug");
			if(pet instanceof Cat)
				counter.count("Cat");
			if(pet instanceof Manx)
				counter.count("EgyptianMau");
			if(pet instanceof Manx)
				counter.count("Manx");
			if(pet instanceof Manx)
				counter.count("Cymric");
			if(pet instanceof Rodent)
				counter.count("Rodent");
			if(pet instanceof Rat)
				counter.count("Rat");
			if(pet instanceof Mouse)
				counter.count("Mouse");
			if(pet instanceof Hamster)
				counter.count("Hamster");
				
		}
		
		print();
		print(counter);
	}
	
	public static void main(String[] args) 
	{
		countPets(new ForNameCreator());
	}

}


前面的那两个帮助类是为了产生一些pet类,而pet类的格式是:

//: typeinfo/pets/Cat.java
package Lesson14TypeInformation.pets;

public class Cat extends Pet {
  public Cat(String name) { super(name); }
  public Cat() { super(); }
} ///:~

输出:

Rat -obj2 Manx -obj2 Cymric -obj2 Mutt -obj2 Pug -obj2 Cymric -obj2 Pug -obj2 Manx -obj2 Cymric -obj2 Rat -obj2 EgyptianMau -obj2 Hamster -obj2 EgyptianMau -obj2 Mutt -obj2 Mutt -obj2 Cymric -obj2 Mouse -obj2 Pug -obj2 Mouse -obj2 Cymric -obj2 
{Rat=2, Cymric=7, Cat=9, Pet=20, Dog=6, Manx=7, EgyptianMau=7, Pug=3, Mouse=2, Rodent=5, Hamster=1, Mutt=3}  obj1




评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值