21 泛型

泛型类泛型演示

泛型可以指定某个特定的类,当使用这个类时,可以设定只传入某种类型的数据。

package cn.xxx.Collection;

public class CollectionTest {
	public static void main(String[] args) {
		MyCollection<String> mc = new MyCollection<>();//泛型的声明,这里的<String>相当于实参
		mc.set("hello", 0);
		String str = (String)mc.get(0);
		System.out.println(str);
	}	
}

class MyCollection<E>{//这里的<E>相当于形参
	Object[] objs = new Object[10];
	
	public void set(E e,int index){
		objs[index] = e;
	}
	
	public E get(int index){
		return (E)objs[index];
	}
}

  

泛型方法演示

使用泛型方法可以不必声明泛型类,泛型仅在被声明的方法内发生。

泛型方法的声明

[权限修饰符] [static] <E> [返回类型] 方法名(E e){

}

  

举个例子:

public class GenericityMethod {
	public static <E> void test(E e){
		System.out.println(e);
	}
	public static void main(String[] args) {
		test("我和你");
		test(111);
	}
}

  

posted @ 2019-11-29 16:40  Scorpicat  阅读(129)  评论(0编辑  收藏  举报