Student stu1; //创建一些Student类的对象
Student stu2;
Student stu3;HashMap<String, Student> myMap = new HashMap<String, Student>();//创建一个HashMap,并把对象放进去
myMap.put("123", stu1);
myMap.put("233", stu2);
myMap.put("213", stu3);for(Student s : myMap.values() ){
s.function(); //function()是Student类的一个方法
}
不过这东西,应该你自己弄的.这样才能映象深刻。import java.util.*;
class Student{
String name;
String id;
//String others;
Student(String id,String name){
this.name=name;
this.id=id;
}
public String getName(){
return name;
}
public String toString(){
return id+" "+name;
}
}
public class Test4{
public static void main(String[] args){
Student[] stus={new Student("001","ZhangSa"),new Student("002","LiSi"),new Student("003","WangWu")};
HashMap<String, Student> myMap = new HashMap<String, Student>();
for(Student s:stus){
myMap.put(s.id , s);
}
for(Student s : myMap.values() ){
String name=s.getName();
System.out.println(name);
}
}
}F:\java>java Test4
ZhangSa
LiSi
WangWu
问题是我写的一个程序里面,有一个类Voteses, 在这个类里面有一个私有属性是一个HashMap,然后我用类Voteses里面的一个函数public HashMap getMap(){...} 在类外来获得这个HashMap属性的句柄,再遍历的时候就有语法错误(Object无法转化为...). 只有把这个属性设为public,直接在类外调用,进行遍历语法才没有语法错误
难道HashMap是不能做为返回类型的么?
还是当HashMap作为返回类型的时候发生了隐式转化?
如public HashMap<String, Votes> getMap(){...}
如果是public HashMap getMap() {...} 好像就发生了隐式转化