package com.imooc.pt;
import java.util.ArrayList;
public class ListSample {
/**
* 不使用泛型
*/
public void sample1(){
//ArrayList不使用泛型,不知道bookList的类型
ArrayList bookList = new ArrayList();
bookList.add("三国演义");
bookList.add("水浒传");
bookList.add(3.1415926f);
Object o1 = bookList.get(0);
String bookName1 = (String)o1;
System.out.println(bookName1.substring(0,1));
Object o2 = bookList.get(2);
String bookName2 = (String)o2;//o2不是字符串
System.out.println(bookName2.substring(0,1));//出错
}
/**
* 使用泛型
*/
public void sample2(){
//使用泛型限制bookList只能接受字符串类型的数据
ArrayList<String> bookList = new ArrayList();
bookList.add("三国演义");
bookList.add("水浒传");
//bookList.add(3.1415926f);
String bookName1 = bookList.get(0);
System.out.println(bookName1.substring(0,1));
Object o2 = bookList.get(2);
String bookName2 = (String)o2;
System.out.println(bookName2.substring(0,1));
}
public static void main(String[] args) {
ListSample listSample = new ListSample();
listSample.sample1();
}
}
package com.imooc.pt;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* 自定义泛型
* @param <E>
*/
public class CollectionUtils<E> {
private List<E> data = new ArrayList();
/**
* 添加元素
* @param element
*/
public void add(E element){
data.add(element);
}
/**
* 随机获取List中的元素
* @return
*/
public E randomSelect(){
int idx = new Random().nextInt(data.size());
E ret = data.get(idx);
return ret;
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
CollectionUtils<String> utils = new CollectionUtils();
utils.add("张三");
utils.add("李四");
utils.add("王五");
utils.add("赵六");
String name = utils.randomSelect();
System.out.println(name);
System.out.println(utils.randomSelect());
System.out.println(utils.randomSelect());
System.out.println(utils.randomSelect());
System.out.println(utils.randomSelect());
System.out.println(utils.randomSelect());
System.out.println(utils.randomSelect());
}
}