请将查找目标的过程定义为类方法,查找时直接调用类方法
import java.util.HashMap;
public class HashMapExample
{
public static void main(String[] args) throws Exception
{
HashMap<String , student> students = new HashMap<String, student>();
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();
}
}
}
__________________________________________________________________
public class student
{
private String name;
private String idNo;
public student(String i,String n){
name=n;
idNo=i;
}
public String getName() {
return name;}
public String getIdNo() {
return idNo;}
}
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);}
catspeake
相关分类