java map 自定义类型函数调用

import java.util.*;
class student
{

String name;
int score;
student(String name,int score)
{
this.name=name;
this.score=score;

}

void shuchu()
{
System.out.println(name+" "+score);

}

}
public class banji_1
{
public static void main(String ag[])
{

Map aa=new TreeMap();
aa.put(0,new student("a",1));
aa.put(1,new student("b",2));
aa.put(2,new student("c",3));
for(int i=0;i<4;i++)
{
aa.get(i).shuchu();

}

}
}
编译报错

aa.get(i).shuchu();改成((student)aa.get(i)).shuchu();
get()返回的是Object类型需要强制转换成你需要的对象类型
或者在Map声明时就规定泛型追问

Map声明时就规定泛型是Map aa=new TreeMap();这个样子吗?

追答

是的
应该把Map aa=new TreeMap();
改成Map aa=new TreeMap();

追问

我用Map aa=new TreeMap();编译报类型变量数目错误是什么原因

追答

Map aa=new TreeMap();
Map中要输入两个类型

追问

Integer是作为什么有什么用

追答

aa.put(0,new student("a",1));
你的put里面第一个参数是int类型,第二个是student类型
所以后者写student没有疑问
前者虽然是int型,但是int不是一个类,不能作为泛型的声明
所以就用int的封装类Integer来声明

追问

aa.put(0,new student("a",1));里的0不是作为KEY在Map aa=new TreeMap();也是需要写上的吗?

温馨提示:内容为网友见解,仅供参考
第1个回答  2011-11-18
将for语句改变成下面的就可以了
for(int i=0;i<3;i++)
{

((student) aa.get(i)).shuchu();

}
相似回答