泛型第二遍

来源:互联网 发布:淘宝子账号是什么 编辑:程序博客网 时间:2024/05/07 09:24
泛型 的好处:
1. 把运行时出现 的问题提前至了编译时。
2. 避免了无谓的强制类型转换。

注意: 在泛型中没有多态的概念,两边的数据必须要一致。 或者是只写一边 的泛型类型。


推荐使用: 两边的数据类型都写上一致的。

泛型:

import java.util.ArrayList;public class demo1 {public static void main(String[] args) {ArrayList<String> list=new ArrayList<String>();list.add("aa");list.add("bb");//list.add(12);for (int i = 0; i < list.size(); i++) {String str=list.get(i);System.out.println(str.toUpperCase());}}}

泛型方法:

  当函数中使用了一个不明确的数据类型,那么在函数上就可以进行泛型的定义。

 

        public <泛型的声明> 返回值类型 函数名( 泛型 变量名 ){

        

        

         }

注意:
1. 在方法上的自定义泛型的具体数据类型是调用该方法的时候传入实参的时候确定的。
2. 自定义泛型使用的标识符只要符合标识符的命名规则即可。

public class demo2 {public static void main(String[] args) {Integer i=print(12);String str=print("abc");}public static <T> T print(T o){return o;}}


泛型类:

泛型类的定义格式:

class 类名<声明自定义的泛型>{




注意的事项: 
1. 在类上自定义的泛型的具体数据类型是在创建对象的时候指定的。
2. 在类上自定义了泛型,如果创建该类的对象时没有指定泛型的具体类型,那么默认是Object类型。

//自定义泛型类class Father<T>{private T t;public Father() {// TODO Auto-generated constructor stub}public Father(T t){super();this.t=t;}public void setT(T t) {this.t = t;}public T getT() {return t;}}//泛型类的继承方式1:子类也需要使用泛型class Son1<T> extends Father<T>{}//泛型类的继承方式2:子类指定了具体的类型class Son2 extends Father<String>{}//错误写法,父类上定义有泛型需要进行处理/*class Son3 extends Father<T>{}*/public class demo3 {public static void main(String[] args) {//在类上自定义的泛型的具体数据类型是在创建对象的时候指定的。Father<String> f1=new Father<String>("jack");System.out.println(f1.getT());Father<Integer> f2=new Father<Integer>(20);System.out.println(f2.getT());}}


泛型接口:


泛型接口的定义格式:

interface 接口名<声明自定义的泛型>{

}


在接口上自定义泛型要注意的事项:
1. 在接口上自定义泛型的具体数据类型是在实现该接口的时候指定的。
2. 如果一个接口自定义了泛型,在实现该接口的时候没有指定具体的数据类型,那么默认是Object数据类型。 

interface Inter<T>{void print(T t);}//实现不知为何类型时可以这样定义class myInter<T> implements Inter<T>{@Overridepublic void print(T t) {// TODO Auto-generated method stubSystem.out.println("myprint:"+t);}}//使用接口时明确具体类型。class myInter2 implements Inter<String>{@Overridepublic void print(String t) {// TODO Auto-generated method stubSystem.out.println("myprint2:"+t);}}public class demo4 {public static void main(String[] args) {myInter<String> str=new myInter<String>();str.print("泛型");myInter2 str2=new myInter2();str2.print("只能传字符串");}}




0 0
原创粉丝点击