泛型:
泛型是程序的一种特性。允许程序员在编写代码时定义一些可变的部分,那些部分在使用前必须做出指明。泛型是引用类型,是堆对象主要是引入了类型参数这个概念。
可以直接理解:在定义类型不确定的类型叫泛型;
泛型常规的用法:
public class General_FanXing {
public static void main(String[]args) {
//使用泛型我们就可以减少代码的复用性
//注意<Integer>要使用包装类,不要使用数据类型如:int
Person<Integer> a1 = new Person<Integer>(12,36); //人的坐标可以用x,y轴表示
Person<String> a2 = new Person<String>("北纬12度","东经36度");//可以用经线,和纬线
System.out.println(a1.getIndexX()+"+"+a1.getIndexY());
System.out.println(a2.getIndexX()+"+"+a2.getIndexY());
}
}
//不指定类型,可以不止一个泛型如:<T,E>
class Person<T>{
private T indexX;
private T indexY;
public Person(T indexX, TindexY){
this.indexX = indexX;
this.indexY = indexY;
}
public T getIndexX() {
return indexX;
}
public T getIndexY() {
return indexY;
}
}
定义泛型类时声明数组类型
class ArrayClass<T>{
private T[] array;
public void setT(T[] array){
this.array = array;
}
public T[] getT(){
return array;
}
public static void main(String[] args){
ArrayClass<String> a = new ArrayClass<String>();
String[] array={"a","b","c"};
a.setT(array);
System.out.println(a.getT().length);//如果输出3说明成功
}
}
泛型也可以应用在单独的方法上,示例如下:
public class GenericMethod {
public <T> void printValue(T v) {
String str = v.getClass().getName() + “ = “ + v.toString();
System.out.println(str);
}
}
泛型使用在接口上:
public class GenericInterfaceDemo {
public static void main(String[] args) {
//Student<String> sd = new Student<String>();
Student sd = new Student();
sd.test("hahaha");
}
}
interface Intf<T>{
void test(T aa);
}
第一种实现方法
class Student<T> implements Intf<T>{
public void test(T aa) {
System.out.println(aa);
}
}
第二种实现方法
class Student implements Intf<String>{
public void test(String aa) {
System.out.println(aa);
}
}
使用类型通配符:
public class TongPeiFu_Generic {
public static void main(String[] args) {
// TODO Auto-generated method stub
Test4 t2 = new Test4();
t2.a(new Test3<String>("123","abc"));
}
}
class Test1{
public void a(Test3<?> t){
//通常只用于引用类型上
System.out.println(t);
}
}
class Test2<T>{
private T indexX;
private T indexY;
public Test3(T indexX, T indexY){
this.indexX = indexX;
this.indexY = indexY;
}
}
限制泛型类型范围: //与通配符配合使用
public class TongPeiFu_Generic {
public static void main(String[] args) {
// TODO Auto-generated method stub
Test4 t2 = new Test4();
t2.a(new Test3<String>("123","abc"));
}
}
class Test1{
public void a1(Test3<? extends Number > t){
//extends : 传过来的类型必须是 Number 或 number的子类
System.out.println(t);}
public void a2(Test3<?
super Number > t){
//super : 传过来的类型必须是 Number 或 number的父类类
System.out.println(t);
}
}
class Test2<T>{
private T indexX;
private T indexY;
public Test3(T indexX, T indexY){
this.indexX = indexX;
this.indexY = indexY;
}
}