Ⅰ 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());
}
}
}