黑马程序员技术交流社区
标题:
16天的6为啥不写泛型也不会报友好提示呢
[打印本页]
作者:
BitmapFactory
时间:
2013-3-15 21:36
标题:
16天的6为啥不写泛型也不会报友好提示呢
import java.util.*;
class Student implements Comparable<Student>
{
private String name;
private int age;
Student(String name,int age)
{
this.name = name;
this.age = age;
}
public int compareTo(Student s)
{
int num = new Integer(this.age).compareTo(new Integer(s.age));
if(num==0)
return this.name.compareTo(s.name);
return num;
}
public int hashCode()
{
return name.hashCode() + age*34;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配");
Student s = (Student)obj;
return this.name.equals(s.name) && this.age == s.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name + ":" +age;
}
}
class MapTest
{
public static void main(String[] args)
{
HashMap<Student,String> hm = new HashMap<Student,String>();
hm.put(new Student("lisi1",21),"beijing");
hm.put(new Student("lisi2",22),"shanghai");
hm.put(new Student("lisi3",23),"nanjing");
hm.put(new Student("lisi4",24),"wuhan");
Set<Student> keySet = hm.keySet();
Iterator<Student> it = keySet.iterator();
while(it.hasNext())
{
Student stu = it.next();
String addr = hm.get(stu);
System.out.println(stu + "...." +addr);
}
Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
Iterator<Map.Entry<Student,String>> it1 = entrySet.iterator();
while(it1.hasNext())
{
Map.Entry<Student,String> me = it1.next();
复制代码
//68行这里为啥不写泛型<Student,String>也不会有JVM的友好提示呢
System.out.println(me.getKey()+".."+me.getValue());
}
}
}
复制代码
作者:
IT菜鸟
时间:
2013-3-15 22:09
在泛型中 参数化类型与原始类型有一定的兼容性;参数化类型可以引用一个原始类型的对象,原始类型也可以引用一个参数化类型。编译器应该是报警告,而不是报错。
作者:
BitmapFactory
时间:
2013-3-15 23:13
蔡志刚 发表于 2013-3-15 22:09
在泛型中 参数化类型与原始类型有一定的兼容性;参数化类型可以引用一个原始类型的对象,原始类型也可以引 ...
还是没明白,蔡兄,能不能根据我的代码讲讲呢
作者:
谢洋
时间:
2013-3-16 01:23
//Map.Entry<K,V>类上定义了泛型,如果在应用时不给泛型传入实参数会警告,当我们在这里传入实参数时,
//这个类身上方法用到该类上所定义的<K,V>这两个形参的实际类型就被确定下来了
Set<
Map.Entry<Student,String
>> entrySet = hm.entrySet();//Map.Entry<K,V>类上定义了泛型,如果在应用时不给泛型传入实参数会警告
Iterator<Map.Entry<Student,String>> it1 = entrySet.iterator();
while(it1.hasNext())
{
Map.Entry<Student,String> me = it1.next();//因为上面的<K,V>已被传入实参了,也就是说这时Map.Entry已确定它所操作的数据类型
举个例子:ArrayList<
E
>这是个
数据类型被参数化
的类
1、ArrayList<
String
> al = new ArrayList<
String
>()
al.add(Person);//编译失败:add(
E
e)这是add方法的原型;经过上面的传到ArrayList<E>上的实参String,这里的意思是告诉编译add的形参E实际类型为String,
那里的这里的add方法已变成add(String e);那么这时这个方法就只能传String类的参数
对比:
2、ArrayList al = new ArrayList()
al.add(Person);//编译通过:add(
E
e)这是add方法的原型;上面的没有给ArrayLis<E>的泛型参数传递实参,,
//也就是说这里的add方法参数类型在编译器无法确定,因为编译无法确定参数型,也就知道不会知道你传的参数是否是同一类型,所以会警告你!
al.add("string")//编译通过,运行失败
3、那为什么运行时会出错?
ArrayList al = new ArrayList()
al.add(Person);//
已经把al对象的中用到参数类型已经确了:这里的add方法相当于add(Person p);
al.add("string");//这里就相当于把字符串传给Person 类型的形参,所以就会发生:cast Exception
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2