在HashMap中查找
来源:百度知道 编辑:UC知道 时间:2024/05/11 18:10:23
请将查找目标的过程定义为类方法,查找时直接调用类方法
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();
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();
我把方法改成非静态的了.
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(&quo