package cn.hncu.generic.v1;
import java.util.ArrayList;
import java.util.Iterator;
public class GenericDemo1 {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("a111");
list.add("a222e23");
list.add("a333fdjk23232");
list.add(100);//这一句会导致出现异常
Iterator it = list.iterator();
while(it.hasNext()){
String str = (String) it.next();
System.out.println(str+"---,len:"+str.length());
}
}
}
-----------------------------------------------------
package cn.hncu.generic.v1;
import java.util.ArrayList;
import java.util.Iterator;
public class GenericDemo2 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
//ArrayList<Integer> list = new ArrayList<Integer>();
list.add("a111");
list.add("a222e23");
list.add("a333fdjk23232");
//list.add(100);//泛型的第1个好处:可以把运行期的错误提前到编译期
Iterator<String> it = list.iterator();
while(it.hasNext()){
String str = it.next(); //泛型的第2个好处:不需要类型强转
System.out.println(str+"---,len:"+str.length());
}
}
}
-------------------------------------------
package cn.hncu.generic.v1;
public class MySet<E> {
private E objs[];
@SuppressWarnings("unchecked")
public MySet() {
Object t[] = new Object[0];
objs =(E[])t;
}
@SuppressWarnings("unchecked")
public boolean add(E obj) {
// 判断对象是否已经存在----用卫条件守护
if( contains(obj) ){
return false;
}
// 扩容
Object tempObjs[] = new Object[objs.length + 1];
for (int i = 0; i < objs.length; i++) {
tempObjs[i] = objs[i];
}
tempObjs[objs.length] = obj;
objs = (E[]) tempObjs;
return true;
}
public boolean contains(Object obj){
for(Object o:objs){
if(o.equals(obj)){
return true;
}
}
return false;
}
public E[] getAll(){
return objs;
}
public int size() {
return objs.length;
}
}