-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPetCreator.java
More file actions
45 lines (41 loc) · 1.02 KB
/
Copy pathPetCreator.java
File metadata and controls
45 lines (41 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package chapter11.three;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public abstract class PetCreator {
private Random rand=new Random(47);
//产生一个数组,存放Pet的之类对象
public abstract List<Class<? extends Pet>> types();//抽象方法
/**
* 随机产生pet的一个子类等
* @return
*/
public Pet randomPet(){
int n=rand.nextInt(types().size());
try {
return types().get(n).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public Pet[] createArray(int size){
Pet[] result=new Pet[size];
for (int i = 0; i < result.length; i++) {
result[i]=randomPet();
}
return result;
}
public ArrayList<Pet> arrayList(int size){
List<Pet> list=new ArrayList<Pet>();
for (int i = 0; i < size; i++) {
list.add(randomPet());
}
return (ArrayList<Pet>) list;
}
}