黑马程序员技术交流社区
标题:
泛型应用在自定义类的对象上
[打印本页]
作者:
itheima_llt
时间:
2015-4-17 12:20
标题:
泛型应用在自定义类的对象上
##三、引用数据类型的自定义复杂对象
2 先建立一个Person
3 再建立一个Student继承Person
4 ArrayList<Person> al = new ArrayList<Student>();
左边声明本集合是接受Person的,但是右边只传了Student,
同时在语法上下面如果调用add()方法添加了Person类的子类对象Worker也是可以的,
但是这就出现了安全问题!
因为在Student集合中竟然出现了Worker,这就产生了严重的安全问题!
所以:编译无法通过,左右两边类型不一致!
编译时候会给出这样的提示:
^
需要: ArrayList<Person>
找到: ArrayList<Student>
原因: 无法通过方法调用转换将实际参数ArrayList<Student>转换为ArrayList<Person>
1 个错误
##四、泛型没有使用限定范围
```
import java.util.*;
class GenericDemo6
{
public static void main(String[] args)
{
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); //ArrayList<Person> al = new ArrayList<Student>();错误:左右两边类型不一致,怎么解决呢?<? extends Person>
}
public static void printColl(ArrayList<Person> al)
{
Iterator<Person> it = al.iterator();
while(it.hasNext())
{
System.out.println(it.next().getName());
}
}
}
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);
}
}
```
如果想让左右两边不一致,同时还能通过编译,并且没有安全隐患,该怎么解决呢??
使用<? extends Person>可以接受Person和Person的子类型
这就是泛型的限定。
##五、使用了泛型限定上限
```
import java.util.*;
class GenericDemo6
{
public static void main(String[] args)
{
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); //ArrayList<? extends Person> al = new ArrayList<Student>();error左右两边类型不一致,怎么解决呢?<? extends Person>
}
public static void printColl(ArrayList<? extends Person> al)//能够接受Person和Person的子类对象
{
Iterator<? extends Person> it = al.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
class Person
{
private String name;
Person(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
//覆盖toString
public String toString()
{
return name;
}
}
class Student extends Person
{
Student(String name)
{
super(name);
}
}
```
小结:
<?>任意类型---?是占位符,或者叫通配符
<T>固定类型
<? extends T>T和T的子类。
正如本例中的<? extends Person>可以接受Person和Person的子类。
这就泛型向上限定的,上面是固定的,下面是可以扩展的,不确定的---上限
<? super T>T和T的父类。
<? super Student>可以接受Student和Student的父类。
这就是泛型向下限定的,下面是固定的,上面是可以扩展的,不确定的---下限
当然啦,在本例中是不可以使用下限限定泛型的,因为Object是不具备getName()方法的。
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2