package lesson;
//ArrayList与vector的区别:
//1:vector 是线程同步的(这个类中的一些方法保证了Vector中的对象是线程安全的),ArrayList是线程非同步的(因此ArrayList中的对象并不是线程安全的)
//2:如果填充数据查过出示容量或默认容量(假设为originalSize)时,vector按照originalsize/2自动扩充,而ArrayList则按照originalSize增长
//数据增长:
//从内部实现机制来讲ArrayList和Vector都是使用数组(Array)来控制集合中的对象。
//当你向这二中类型中增加元素的手,如果元素的数码超过了内部数组目前的长度,他们都要扩展内部数组的长度
//Vector缺省情况下自动增长原来一倍的数组长度,ArrayList是原来的50%,所以最后获得的这个集合所占的空间总是比你实际需要的要大,所以如果你要在集合中保存
//大量数据那么使用Vecto有一些优势,因为你可以通过设置集合的初始化大小来避免不必要的资源开销
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Vector;
public class VectorTest
{
public static <E> void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
Vector<Object> v=new Vector<Object>();
Manager emp=new Manager(123,"郑云飞",22);
v.add(emp);
for(int i=0;i<v.size();i++)
{
System.out.println(((Manager)v.get(i)).test(1, "云飞", 22));
System.out.println(v.elementAt(i));
}
Gen<Bird> b=new Gen<Bird>(new Bird("小鹦鹉",6));
b.showTypeName();
}
}
//定义一个Bird类
class Bird
{
private String name;
private int age ;
public Bird(String name, int age) {
super();
this.name = name;
this.age = age;
}
public static Object[] count(int a,int b)
{
System.out.println("鹦鹉算算术的结果是:"+a+b);
return null;
}
}
//定义一个泛型
class Gen<T>
{
T o;
public Gen(T o)
{
this.o=o;
}
public void showTypeName() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
System.out.println("类型是:"+o.getClass());
//通过反射机制,我们可以得到T这个类的很多信息
Method []m=o.getClass().getDeclaredMethods();
//打印
for(int i=0;i<m.length;i++)
{
if(m[i].getName().equals("count"))
{
m[i].invoke(Bird.count(6, 8));
}
}
}
}
package lesson;
class Manager
{
private int id;
private String name;
private int age;
public Manager(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public Manager(int id, String name)
{
super();
this.id = id;
this.name = name;
}
public static int test(int id,String name,int age)
{
System.out.println("编号:"+id+"姓名:"+name+"年龄:"+age);
return age;
}
}
package fxing;
import java.util.*;
public class Gen4Test
{
public static void main(String[] args)
{
Gen4<ArrayList<String>,String> g4=new Gen4<ArrayList<String>,String>();
g4.id=new ArrayList<String>();
g4.id.add("123");
System.out.println(g4.id);
//?泛型通配符,表示任意的数据类型
//使用的时候可以使用extends限定泛型为固定类型一下的对象类型
//Gen4<Collection> g44=null;//err
//g44=new Gen4<HashSet>();//err
Gen4<? extends Collection,String> g44=null;
g44=new Gen4<HashSet,String>();
//super限定泛型为固定类型以上的对象类型
//super只能在使用的使用限定,不能在声明的时候限定
Gen4<? extends Collection,? super List> gg4=null;
gg4=new Gen4<LinkedList,Collection>();
gg4.<Object>getM("123");
System.out.println(gg4.<String>getT("456"));
}
}
package fxing;
import java.util.*;
public class Gen4<o extends Collection,E>//声明泛型的时候可以用extends限定泛型为固定类型一下的对象类型
{
o id;
E e;
public o getId()
{
return id;
}
//方法的泛型
public <M> void getM(String m)
{
}
public <T> T getT(T t)
{
return t;
}
}