Java基础——泛型

 

泛型:JDK1.5版本以后出现新特性。用于解决安全问题,是一个类型安全机制。

未加泛型的时候编译出现的注意提示:

加泛型限定,不仅编译通过,编译出现的注意提示也会不见;

好处:

1. 将运行时期出现问题ClassCastException,转移到了编译时期。方便于程序员解决问题。让运行时问题减少,安全。

2.避免了强制转换麻烦。

3.实现了代码的抽取,提高了开发效率。比如我们对数据的操作,如果我们有多个实体,每个实体都有增删改查方法,这些方法基本都是通用的,因此我们可以抽取出一个BaseDao<T>,里面提供CRUD方法,这样我们操作谁只需要将我之前提到的三个类作为泛型值传递进去就可以。
还有网络请求的响应数据格式一般为{"code":"","data":{}},data可能是不同的对象,集合,字符串等,这时就可以抽取出一个BaseResponse<T>,data对应什么对象泛型值就传什么。

缺点:

不能使用类型特有方法;

 

泛型格式:

通过<>来定义要操作的引用数据类型。

如:ArrayList<E>类和ArrayList<Integer>

1、ArrayList<E>整个称为泛型类型

2、ArrayList<E>中的E称为类型变量或类型参数

3、整个ArrayList<Integer>称为参数化类型

4、ArrayList<Integer>中的Integer称为类型参数的实例或实际类型参数

5、ArrayList<Integer>中的<>称为typeof

6、ArrayList称为原始类型

参数化:parametered,已经将参数变为实际类型的状态。

 

在使用java提供的对象时,什么时候写泛型呢?

通常在集合框架中很常见,

只要见到<>就要定义泛型。

其实<> 就是用来接收类型的。

当使用集合时,将集合中要存储的数据类型作为参数传递到<>中即可。

 

关于参数化类型的几点说明:

1、参数化类型与原始类型的兼容性

        第一、参数化类型可引用一个原始类型的对象,编译只是报警告。

        如:Collection<String> coll = new Vector();

        第二、原始类型可引用一个参数化类型的对象,编译报告警告

        如:Collectioncoll = new Vector<String>();

        原来的方法接受一个集合参数,新类型也要能传进去。

2、参数的类型不考虑类型参数的继承关系:

        Vector<String> v = newVector<Objec>();//错误的

        不写Object没错,写了就是明知故犯

        Vector<Objec> v = newVector<String>();//错误的

3、编译器不允许创建泛型变量的数组。即在创建数组实例时,数组的元素不能使用参数化的类型

        如:Vector<Integer>vectorList[] = new Vector<Integer>[10];//错误的

        //下面两种方式可以创建泛型数组
        Vector<Integer>[] vectors = new Vector[10];
        Vector<String>[] vectors1 = (Vector<String>[]) new Vector[10];

泛型只在编译阶段有效,泛型检验后会将泛型信息擦除

ArrayList<String> a = new ArrayList<>();
ArrayList b = new ArrayList();
Class c1 = a.getClass();
Class c2 = b.getClass();
System.out.println(c1 == c2); //结果为true

上面程序的输出结果为true。因为所有反射的操作都是在运行时的,既然为true,就证明了编译之后,程序会采取去泛型化的措施。

也就是说Java中的泛型,只在编译阶段有效。在编译过程中,正确检验泛型结果后,会将泛型的相关信息擦出,并且在对象进入和离开方法的边界处添加类型检查和类型转换的方法。成功编译过后的class文件中是不包含任何泛型信息的。

 

上述结论可通过下面反射的例子来印证:

//通过反射验证泛型擦除
ArrayList<String> a = new ArrayList<>();
a.add("String");
Class c = a.getClass();
try{
    Method method = c.getMethod("add",Object.class);
    method.invoke(a,100);
}catch(Exception e){
    e.printStackTrace();
}
System.out.println("反射验证编译后的class文件中,泛型已经被擦除"+a);//绕过了编译阶段也就绕过了泛型,输出a:[String, 100]

1.   泛型使用

在集合中使用泛型:

class GenericDemo 

{

         public static void main(String[] args) 

         {

 
                   ArrayList<String> al = new ArrayList<String>();

                   al.add("abc01");

                   al.add("abc0991");

                   al.add("abc014");

                   //al.add(4);//al.add(new Integer(4));//编译不通过

                   
                   Iterator<String> it = al.iterator();//把数据装到迭代器,也加泛型限定,不仅编译通过,编译出现的注意提示也会不见;

                   while(it.hasNext())

                   {

                            String s = it.next();

                            System.out.println(s+":"+s.length());

                   }

         }

}

在接口中添加具体泛型类型:

import java.util.*;

class GenericDemo2 

{

         public static void main(String[] args) 

         {
                 TreeSet<String> ts = new TreeSet<String>(new LenComparator());
                 ts.add("abcd");
                 ts.add("cc");
                 ts.add("cba");

                 Iterator<String> it = ts.iterator();
                 while(it.hasNext())

                 {
                    String s = it.next();
                    System.out.println(s);
                 }

         }

}


class LenComparator implements Comparator<String>//在接口中添加具体的泛型类型
{

    public int compare(String o1,String o2)

    {

        int num = new Integer(o2.length()).compareTo(new Integer(o1.length()));//o2在前,由长到短显示。o1在前,由短到长显示;

        if(num==0)

            return o2.compareTo(o1);

        return num;

    }

}

2.   泛型类

/*

class Tool

{

         private Worker w;

         public void setWorker(Worker w)

         {

                   this.w = w;

         }

         public Worker getWorker()

         {

                   return w;

         } 

}

一个工具类只能创建一种类的对象

*/ 

 

class Worker

{

 

}

class Student

{

}

//泛型前做法。虽然一种工具类能获取多种类的对象,但是要明确set出的对象和获取的是同一个类的对象;要强转;

class Tool

{

         private Object obj;

         public void setObject(Object obj)

         {

                   this.obj = obj;

         }

         public Object getObject()

         {

                   return obj;

         }

}

 

//泛型类。

/*

什么时候定义泛型类?

当类中要操作的引用数据类型不确定的时候,

早期定义Object来完成扩展。

现在定义泛型来完成扩展。

*/

    static class Utils<QQ>
    {
        private QQ q;//使用QQ类型定义变量

        public Utils(){};

        //使用QQ类型的形参定义构造方法
        public Utils(QQ q){
            this.q = q;
        }

        public void setObject(QQ q)
        {
            this.q = q;
        }

        public QQ getObject()
        {
            return q;
        }

    }

 

 

class  GenericDemo3

{

         public static void main(String[] args) 

         {

 

                   Utils<Worker> u = new Utils<Worker>();

                   u.setObject(new Student());//编译出错,问题出现在编译时期;

                   Worker w = u.getObject();;

 

             //Utils泛型的是worker类,所以new student()对象在编译时期就会出错;

                   /*泛型前的做法,需要强转

                   Tool t = new Tool();

                   t.setObject(new Student());

                   Worker w = (Worker)t.getObject();

                   */

         }

}

3.   泛型方法,泛型静态方法

 

/*

class Demo<T>

{

         public void show(T t)

         {

                   System.out.println("show:"+t);

         }

         public void print(T t)

         {

                   System.out.println("show:"+t);

         }

 

}

*/

 

//泛型类定义的泛型,在整个类中有效。如果被方法使用,

//那么泛型类的对象明确要操作的具体类型后,所有要操作的类型就已经固定了。

//

//为了让不同方法可以操作不同类型,而且类型还不确定。

//那么可以将泛型定义在方法上。

 

 

/*

特殊之处:

静态方法不可以访问类上定义的泛型。

如果静态方法操作的应用数据类型不确定,可以将泛型定义在方法上。

 

*/

 

class Demo<T>//T要建立对象的时候才明确;

{

         public  void show(T t)

         {

                   System.out.println("show:"+t);

         }

         public <Q> void print(Q q)

         {

                   System.out.println("print:"+q);

         }

         public  static <W> void method(W t)//泛型定义在返回值类型的前面

         {

                   System.out.println("method:"+t);

         }

}

class GenericDemo4 

{

         public static void main(String[] args) 

         {

                   Demo <String> d = new Demo<String>();

                   d.show("haha");

                   //d.show(4);//编译不通过

                   d.print(5);

                   d.print("hehe");

 

                   Demo.method("hahahahha");

 

                   /*

                   Demo d = new Demo();

                   d.show("haha");

                   d.show(new Integer(4));

                   d.print("heihei");

                   */

                   /*

                   Demo<Integer> d = new Demo<Integer>();

                   d.show(new Integer(4));

                   d.print("hah");

 
                   Demo<String> d1 = new Demo<String>();

                   d1.print("haha");

                   d1.show(5);//编译不通过

                   */

         }

}

4.   泛型接口

//泛型定义在接口上。

interface Inter<T>

{

         void show(T t);

}

 

/*

class InterImpl implements Inter<String>

{

         public void show(String t)

         {

                   System.out.println("show :"+t);

         }

}

 

*/

 

class InterImpl<T> implements Inter<T>

{

         public void show(T t)

         {

                   System.out.println("show :"+t);

         }

}

class GenericDemo5 

{

         public static void main(String[] args) 

         {

 

                   InterImpl<Integer> i = new InterImpl<Integer>();

                   i.show(4);

                   //InterImpl i = new InterImpl();

                   //i.show("haha");

         }

}

5.   泛型限定(泛型的高级应用)

通配符:

当传入的类型不确定时,可以使用通配符?。也可以理解为占位符。使用通配符的好处是可以不用明确传入的类型,这样在使用泛型类或者泛型方法时,提高了扩展性。

Collection<?>  a可以与任意参数化的类型匹配,但到底匹配的是什么类型,只有以后才知道,所以:a=newArrayList<Integer>和a=new ArrayList<String>都可以,但a.add(new Date())或a.add(“abc”)都不行。

 

泛型的限定;

? extends E: 可以接收E类型或者E的子类型。上限。较常用

? super E: 可以接收E类型或者E的父类型。下限

 

泛型限定用于泛型扩展运用的

 如:

import java.util.*;

class  GenericDemo6

{

         public static void main(String[] args) 

         {

                   /*

                   ArrayList<String> al = new ArrayList<String>();

                   al.add("abc1");

                   al.add("abc2");

                   al.add("abc3");

 

                   ArrayList<Integer> al1 = new ArrayList<Integer>();

                   al1.add(4);

                   al1.add(7);

                   al1.add(1);

 

                   printColl(al);

                   printColl(al1);

                   */

 

                   ArrayList<Person> al = new ArrayList<Person>();

                   al.add(new Person("abc1"));

                   al.add(new Person("abc2"));

                   al.add(new Person("abc3"));

                   //printColl(al);

 

                   ArrayList<Student> al1 = new ArrayList<Student>();

                   al1.add(new Student("abc--1"));

                   al1.add(new Student("abc--2"));

                   al1.add(new Student("abc--3"));

                   printColl(al1);  

//当printColl ()方法没有泛型限定时,ArrayList< Person> al = new ArrayList<Student>();error,因为编译时提示会出现类型安全问题,如:窝里住动物,但是只能住猪

         }

         public static void printColl(Collection<? extends Person> al)

         {

                   Iterator<? extends Person> it = al.iterator();

                   while(it.hasNext())

                   {

                            System.out.println(it.next().getName());

                   }

         }

         /*

         public static void printColl(ArrayList<?> al)

//当该方法用String限定时,ArrayList<String> al = new ArrayList<Integer>();error

//改为通配符编译通过;但是不严谨。

//如果用?,则不明确类型,不能使用类型特有方法

         {

                   Iterator<?> it = al.iterator();

                   while(it.hasNext())

                   {

                            System.out.println(it.next().toString());

                   }

         }

         */

}

 

class Person

{

         private String name;

         Person(String name)

         {

                   this.name = name;

         }

         public String getName()

         {

                   return name;

         }

}

 

class Student extends Person

{

         Student(String name)

         {

                   super(name);

         }

 

}


/*

 

class Student implements Comparable<Person>//<? super E>

{

         public int compareTo(Person s)

         {

                   this.getName()

         }

}

*/

class Comp implements Comparator<Person>

{

         public int compare(Person s1,Person s2)

         {

 

                   //Person s1 = new Student("abc1");//编译通过

                   return s1.getName().compareTo(s2.getName());

         }

}

 

TreeSet<Student> ts = new TreeSet<Student>(new Comp());

ts.add(new Student("abc1"));

ts.add(new Student("abc2"));

ts.add(new Student("abc3"));

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java静态属性泛型是指在Java,我们可以在静态属性上使用泛型类型。通过在静态属性的类型声明添加泛型参数,我们可以在静态属性使用泛型类型,从而使静态属性具有泛型的特性。 举例来说,我们可以定义一个拥有泛型类型的静态属性,如下所示: public class MyClass<T> { public static T staticField; } 在上面的例子,我们通过在静态属性staticField的类型声明添加了泛型参数T,使得静态属性具有泛型的特性。这样,我们就可以根据实际情况在不同地方使用不同类型的静态属性。 需要注意的是,在静态属性使用泛型类型时,由于静态属性属于类而不是对象,所以泛型类型参数不能是实例化类型,而必须是类级别的类型。也就是说,不能使用泛型类型参数T来实例化静态属性,而只能使用具体的类型来实例化。 因此,使用静态属性时,我们需要确保在静态属性的类型声明正确地使用泛型类型参数,并在使用时传入具体的类型来实例化静态属性。这样,就可以在静态属性使用泛型类型了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Java 泛型(两万字超全详解)](https://blog.csdn.net/weixin_45395059/article/details/126006369)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值