Java泛型机制

泛型程序设计

一、泛型程序设计的起源?java

泛型是JDK1.5增长的新特数组

二、使用泛型的好处?安全

使用泛型机制编写的代码比那些杂乱使用Object变量,而后再进行强制类型转换的代码具备更好的安全性和可读性。spa

public class GenericTest01 {

public static void main(String[] args) {

/*
// 建立一个集合
List list = new ArrayList();

// 建立对象
Cat c = new Cat();
Bird b = new Bird();

// 添加对象
list.add(c);
list.add(b);

// 遍历集合
Iterator integer = list.iterator();
while (integer.hasNext()) {
Object obj = integer.next();
if (obj instanceof Animal) {
Animal a = (Animal)obj;
a.move();
}
}*/

// 建立集合,使用泛型
List<Animal> list = new ArrayList<Animal>();
Cat c = new Cat();
Bird b = new Bird();

list.add(c);
list.add(b);

// 获取迭代器
// 这个表示迭代器迭代的是Animal类型
Iterator<Animal> iterator = list.iterator();
while (iterator.hasNext()) {
Animal a = iterator.next();
a.move();
}
  }
}
class Animal {
public void move() {
System.out.println("动物在移动");
}
}

class Cat extends Animal {
public void CatchMouse() {
System.out.println("猫抓老鼠!");
}
}

class Bird extends Animal {
public void Fly() {
System.out.println("鸟儿在飞翔!");
}
}

三、泛型的缺点是什么?
使集合中的元素单一,可是在大多数业务中,集合中的元素是统一的,因此这种新特性逐渐被你们承认。

四、砖石表达式
JDK8以后引入了:自动类型推断机制。(又称为砖石表达式)
public class GenericTest02 {
public static void main(String[] args) {

// 使用泛型,建立一个Animal类型的数组
List<Animal> list = new ArrayList<>();

// 添加元素
list.add(new Animal());
list.add(new Cat());
list.add(new Bird());

// 遍历集合
// 不使用泛型默认返回的是Object类型
Iterator<Animal> iterator = list.iterator();
while (iterator.hasNext()) {
Animal animal = iterator.next();
animal.move();
}

List<String> stringList = new ArrayList();

// 类型不匹配
// stringList.add(new Animal());
// stringList.add(123);
// stringList.add(new Object());

// 添加元素
stringList.add("http://www.baidu.com");
stringList.add("http://www.4399.com");
stringList.add("http://www.7k7k.com");

// 遍历

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

/* 若是没有使用泛型,如下代码就得这样写
Object o = it.next();
if (o instanceof String) {
String s1 = (String) o;
String newString = s1.substring(7);
System.out.println(newString);
}*/
// 直接经过迭代器获取了String类型的数据
String s = it.next();
String s1 = (String) s;
String newString = s1.substring(7);
System.out.println(newString);
}
}
}
五、自定义泛型

自定义泛型的时候,尖括号中是一个标识符,能够随便写。
java源代码中常常出现的是:<E>和<T> E是Element首字母大写,T是Tyte首字母大写
 
public class GenericTest03<A> {    public void doSome(A o) {        System.out.println(o);    }    public static void main(String[] args) {        GenericTest03<String> gt1 = new GenericTest03<>();        // 类型不匹配        // gt1.doSome(100);        gt1.doSome("abc");        GenericTest03<Integer> gt2 = new GenericTest03<>();        // 类型不匹配        // gt2.doSome("abc");        gt2.doSome(100);        GenericTest03 gt3 = new GenericTest03<>();        gt3.doSome(new Object());        MyIterator<String> mi = new MyIterator<>();        String s1 = mi.get();        MyIterator<Animal> mi2 = new MyIterator<>();        Animal a1 = mi2.get();    }}class MyIterator<T> {    public T get() {        return null;    }}
相关文章
相关标签/搜索