泛型

定义:

        将对象的类型作为参数,指定到其他类或者方法上,从而保证类型转换的安全性和稳定性。本质是参数化类型。

特点:

        使用时必须遵守其类型约束,要么是其要求的类型,要么是其要求类型的子类。

泛型方法定义:

package test;

public class FXMethod{

// public void show(Integer integer){

// System.out.println(integer);

// }

// public void show(Boolean bl){

// System.out.println(bl);

// }

// public void show(String string){

// System.out.println(string);

// }

/*

* 通过观察,以上的方法构成了重载(方法名相同,参数不同,当然与修饰符、返回类型无关)

* 所以使得代码比较冗余

* 但泛型方法可以很好的解决以上代码冗余问题

*/

//以下为错误泛型写法

//public FXMethod (){

// super();

// }

public void show(T1 t1,T2 t2,T3 t3,T4 t4){

System.out.println("T1为:"+t1+"\tT2为:"+t2+"\tT3为:"+t3+"\tT4为:"+t4);

}

public static void main(String[] args) {

FXMethod   fXMethod2 = new    FXMethod();

fXMethod2.show(true, 0,"hello",8F);

}

}

泛型集合定义:

package test;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.Set;

class Students{

private String name;

private String sex;

public Students() {

super();

}

public Students(String name, String sex) {

super();

this.name = name;

this.sex = sex;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getSex() {

return sex;

}

public void setSex(String sex) {

this.sex = sex;

}

}

public class HashMapDemo {

public static void main(String[] args) {

Students student1 = new Students("李明","男");

Students student2 =new Students("王丽","女");

Students student3= new Students("张三","男");

 Map   map = new   HashMap();

 Map   map2 = new  =   HashMap();

map.put("jack", student1);

map.put("lucy", student2);

map.put("john", student3);

//获取所有的键

Set    set   = map.keySet();

System.out.println("遍历方式1:Iterator");

Iterator iter = set.iterator();

while(iter.hasNext()){

// Object str1 = iter.next();

//因为str1为对象,所以应该输出的是地址,

//但因为String类重写了输出对象方法,所以输出的为值

// System.out.print(str1+"\t");//john lucy jack

// String str = (String)iter.next();//理由同上

// System.out.print(str+"\t");//john lucy jack

String str = iter.next();

Students stu = map.get(str);

System.out.println(str+"对应的学员姓名是:"+stu.getName()+"\t性别是:"+stu.getSex());

}

System.out.println("---------------------------------------");

System.out.println("遍历方式2:foreach");

for (String obj: set) {

Students stu2 = map.get(obj);

System.out.println(obj+"对应的学员姓名是:"+stu2.getName()+"\t性别是:"+stu2.getSex());

}

}

}

泛型接口定义:

第一种不实现泛型接口(推荐)
第二种实现泛型接口(不推荐)
1不实现的时候,pet的类型


2不实现的时候,pet的类型 

 泛型类定义:

注意事项:

之后即可调用排序方法对对象进行排序
底层是通过-1,0,1进行排序的

你可能感兴趣的:(泛型)