这篇文章主要介绍了java编程泛型限定的相关内容,具有一定参考价值,需要的朋友可以了解下。
泛型 一般 出现在集合中,迭代器中 也会出现!
泛型 是为了 提高代码的 安全性。 泛型 确保数据类型的唯一性。
在我们常用的容器中, 越是单一越好处理啊!
泛型的限定:
? 是通配符 指代 任意类型
泛型的限定上限:
3371dff536b4806b35a8d9de00b666f6 接受 e 或者 e 的子类型。
泛型的限定下限:
857d4dde8afb935d7244a5d6c08570c4 接收 e 或者 e 的父类。
泛型的限定上限 (定义父类 填装子类 类型!)
下面我们看看具体代码示例
package newfeatures8;
import java.util.*;
/*
? 通配符。也可以理解为占位符。
泛型的限定;
? extends e: 可以接收e类型或者e的子类型。上限。
? super e: 可以接收e类型或者e的父类型。下限
*/
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<student>();error
//为了解决等号两边泛型不一致的情况,jdk1.7以后可以这么写
arraylist<person> al = new arraylist<>();//右边的泛型自动反射进来
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);
}
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)
{
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> {
public int compareto(person s){
this.getname()
}
}
*/
/*
class comp implements comparator<person>{ //<? super e>
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());//treeset(comparator<? super e> comparator)
ts.add(new student("abc1"));
ts.add(new student("abc2"));
ts.add(new student("abc3"));
*/
总结
以上就是java中泛型限定的代码分享的详细内容。