HASHMAP最好与实例联系起来..它主要存的是键与值的关系.
举个例子如你现在有一个学生类
import java.util.HashMap;
public class Student {
String name;
String sex;
public Student(String n,String s) {
name=n;
sex=s;
}
public String toString(){
return ("姓名:"+name+"
"+"性别:"+sex+"
");
}
public static void main(String [] args){
HashMap hm=new HashMap();
Student s1=new Student("张三","男");
Student s2=new Student("李四","男");
Student s3=new Student("小利","女");
//存值是根据学生编号存的学生信息
hm.put("001",s1);
hm.put("002",s2);
hm.put("003",s3);
//查找学生编号是001的学生
//因为hm.get("001")反回的是Object所以加上强转
Student s=(Student)hm.get("001");
System.out.println(s.toString());
//其余的类似
}
}
HashMap和ArrayList结合起来用,向HashMap中存值时 把name存入ArrayList中:
HashMap a = new HashMap();
ArrayList al = new ArrayList();
a.put("name1", "abcdef"); // key是name,value是字符串abcdef
al.add("name1");
a.put("name2","me");
al.add("name2");
a.put("name3","you");
al.add("name3");
a.put("name4","he");
al.add("name4");
for(int i=0;i<al.size();i++){
System.out.println(a.get(al.get(i)));
}
HashMap实现的接口有:Serializable, Cloneable, Map<K,V> ,没有实现Cllection接口。
在父类写一个返回hashmap的方法
再直接调用试试