1 回答
TA贡献1111条经验 获得超0个赞
我把方法改成非静态的了.
package testmap;
import java.util.HashMap;
public class Test
{
static HashMap<String , Student> students = new HashMap<String, Student>();
public static void main(String[] args) throws Exception
{
new Test().go();
}
public void go(){
Student s1 = new Student("12345-12","AAA");
Student s2 = new Student("98765-00","BBB");
Student s3 = new Student("55667-99","CCC");
students.put(s1.getIdNo(),s1);
students.put(s2.getIdNo(),s2);
students.put(s3.getIdNo(),s3);
String id = "98765-00";
System.out.println("Let's try to retrive a Student with ID = "+ id);
Student x = students.get(id);
if (x!=null)
{
System.out.println("Found! Name = "+ x.getName());
}
else {
System.out.println("Invalid ID: "+ id);}
System.out.println();
id="00000-00";
System.out.println("Let's try to retrive a Student with ID = "+ id);
x=students.get(id);
if (x!=null)
{
System.out.println("Found! Name = "+x.getName());
}
else {
System.out.println("Invalid ID: "+id);}
System.out.println();
System.out.println("Here are all of the student: ");
System.out.println();
for (Student s : students.values() )
{
System.out.println("ID: "+s.getIdNo());
System.out.println("Name: "+s.getName());
System.out.println();
}
findById("00000-00");
findById("98765-00");
}
public static void findById(String id){
System.out.println("Let's try to retrive a Student with ID = "+ id);
Student x=students.get(id);
if (x!=null)
{
System.out.println("Found! Name = "+x.getName());
}
else {
System.out.println("Invalid ID: "+id);}
}
}
添加回答
举报