Ⅰ java hashmap的用法
已经给楼主写了个例子..
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
public class HashMapTest {
public static void main(String[] args){
HashMap<String,Object> hm=new HashMap<String,Object>();
People p1=new People();
People p2=new People();
People p3=new People();
People p4=new People();
hm.put("People3", p1);
hm.put("People1", p2);
hm.put("People4", p3);
hm.put("People2", p4);
Iterator<String> it=hm.keySet().iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
class People {
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
运行了没问题..
祝楼主早日成功!
Ⅱ java中hashmap的应用,本人小白,这题要咋搞
importjava.util.HashMap;
importjava.util.Map;
publicclasswork{
publicstaticvoidmain(String[]args){
classStudent{//定义内部类Student
privateStringnum;//学号
privateStringname;//名称
privateintage;//年龄
Student(){
}//无参构造方法
Student(Stringnum,Stringname,intage){//有参构造方法
this.num=num;
this.name=name;
this.age=age;
}
publicStringgetNum(){
returnnum;
}
publicvoidsetNum(Stringnum){
this.num=num;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicintgetAge(){
returnage;
}
publicvoidsetAge(intage){
this.age=age;
}
@Override
publicStringtoString(){//复写toString方法
return"学号:"+this.num+",姓名:"+this.name+",年龄:"+this.age;
}
}
Map<String,Student>staff=newHashMap<String,Student>();
Studentstudent1=newStudent("15H001","唐僧",40);//用有参构造方法创建一个学生
Studentstudent2=newStudent();//用无参构造方法创建一个学生
student2.setNum("15H002");
student2.setName("孙悟空");
student2.setAge(2000);
Studentstudent3=newStudent("15H003","猪八戒",1000);//用有参构造方法创建一个学生
staff.put(student1.getNum(),student1);//1号学生放入hashMap
staff.put(student2.getNum(),student2);//2号学生放入hashMap
staff.put(student3.getNum(),student3);//3号学生放入hashMap
System.out.println("3.根据key(学号)查找学号为15H003和15H004的学生,如果存在则输出其学号、姓名、年龄信息,否则输出相应的提示信息");
String[]nums={"15H003","15H004"};
for(inti=0;i<nums.length;i++){
System.out.println("查找学号:"+nums[i]);
Studentstudent=staff.get(nums[i]);
if(student!=null){//如果找到了
System.out.println("学号:"+student.getNum()+",姓名:"+student.getName()+",年龄:"+student.getAge());
}else{//如果没有找到
System.out.println("学号:"+nums[i]+"的学生没有擦寻到相关信息");
}
}
System.out.println("4.输出所有学生的信息");
for(Map.Entry<String,Student>entry:staff.entrySet()){
Stringkey=entry.getKey();
Studentvalue=entry.getValue();
System.out.println("学号:"+key+",姓名:"+value.getName()+",年龄:"+value.getAge());
}
System.out.println("5.移除唐僧");
staff.remove("15H001");//根据唐僧的学号移除唐僧
System.out.println("6.把HashMap变成数组,并输出每个数组元素的信息(学号、姓名、年龄)");
Object[]values=staff.values().toArray();
for(inti=0;i<values.length;i++){
Studentstudent=(Student)values[i];
System.out.println(student.toString());
}
}
}