为了账号安全,请及时绑定邮箱和手机立即绑定

java map 自定义类型函数调用?

java map 自定义类型函数调用?

喵喔喔 2019-02-06 11:07:11
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();}}}编译报错
查看完整描述

2 回答

?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

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

查看完整回答
反对 回复 2019-03-20
?
芜湖不芜

TA贡献1796条经验 获得超7个赞

将for语句改变成下面的就可以了
for(int i=0;i<3;i++)
{

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

}

查看完整回答
反对 回复 2019-03-20
  • 2 回答
  • 0 关注
  • 792 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信