import java.util.Vector;
class Gopher{
private int gopherNumber;
Gopher(int i){
gopherNumber = i;
}
void print(String msg){
if(msg != null){
System.out.println(msg);
}
System.out.println("Gopher number = " + gopherNumber);
}
}
class GopherTrap{
static void caughtYa(Gopher m){
m.print("Caught one!");
}
}
class GopherVector{
private Vector v = new Vector();
public void addElement(Gopher m){
v.addElement(m);
}
public Gopher elementAt(int index){
return (Gopher)v.elementAt(index);
}
public int size(){
return v.size();
}
}
public class WorksAnyway{
public static void main(String[] args) {
GopherVector gophers = new GopherVector();
for(int i=0; i<3; i++){
gophers.addElement(new Gopher(i));
}
for(int i=0; i<gophers.size(); i++){
System.out.println("Free mouse: " + gophers.elementAt(i));
GopherTrap.caughtYa(gophers.elementAt(i));
}
}
class Gopher{
private int gopherNumber;
Gopher(int i){
gopherNumber = i;
}
void print(String msg){
if(msg != null){
System.out.println(msg);
}
System.out.println("Gopher number = " + gopherNumber);
}
}
class GopherTrap{
static void caughtYa(Gopher m){
m.print("Caught one!");
}
}
class GopherVector{
private Vector v = new Vector();
public void addElement(Gopher m){
v.addElement(m);
}
public Gopher elementAt(int index){
return (Gopher)v.elementAt(index);
}
public int size(){
return v.size();
}
}
public class WorksAnyway{
public static void main(String[] args) {
GopherVector gophers = new GopherVector();
for(int i=0; i<3; i++){
gophers.addElement(new Gopher(i));
}
for(int i=0; i<gophers.size(); i++){
System.out.println("Free mouse: " + gophers.elementAt(i));
GopherTrap.caughtYa(gophers.elementAt(i));
}
}
}
结果:
Free mouse: zz.Gopher@2af081
Caught one!
Gopher number = 0
Free mouse: zz.Gopher@53fb57
Caught one!
Gopher number = 1
Free mouse: zz.Gopher@19a32e0
Caught one!
Gopher number = 2
用Vector创建一个新类,使其只接受我们指定的类型,也只生成我们希望的类,会使程序更加健壮,但却也更加沉闷。