泛型
泛型是带一个或多个类型参数(type parameters)的类或者接口, 其声明的格式为:
class 类名称<泛型列表>
泛型列表中可以有任意多个泛型,中间用逗号间隔,它们可以是任何 类或接口,但不能是基本类型数据。
第一题
源代码:
public class shangji08 {
public static class People<E> {
private E pets;
void set(E e){
this.pets = e;
}
E showPets(){
return pets;
}
}
public static class Dog {
String name ;
Dog(String name){
this.name = name;
}
}
public static class Cat {
String name ;
Cat(String name){
this.name = name;
}
}
public static void main(String[] args) {
People<Dog> dog = new People<Dog>();
dog.set(new Dog("xiugou"));
System.out.println("The name of this pet is " + dog.showPets().name);
People<Cat> cat = new People<Cat>();
cat.set(new Cat("maomao"));
System.out.println("The name of this pet is " + cat.showPets().name);
}
}
第二题
源代码:
import java.util.LinkedList;
public class shangji0802{
public static void main(String[] args) {
Player bofangqi = new Player();
Song s1 = new Song("我是老6", "wjh");
Song s2 = new Song("姬霓太美", "刀刀");
bofangqi.addSong(s1);
bofangqi.play(1);
bofangqi.addSong(s2);
bofangqi.play(2);
bofangqi.removeSong(2);
bofangqi.play(2);
}
}
class Player{
LinkedList<Song> songList = new LinkedList<>();
void addSong(Song s){
songList.add(s);
}
void removeSong(int i ){
songList.remove(i-1);
}
void play(int i){
if (i > songList.size()){
System.out.println("超出歌单长度!");
}
else {
System.out.println("第" + i + "首歌的歌手为:" + songList.get(i-1).singer + " 歌名为:" +songList.get(i-1).name);
}
}
}
class Song{
String name;
String singer;
public Song(String name, String singer) {
this.name = name;
this.singer = singer;
}
}