Java HashMap Example: Student Management with HashMap
public class Student {
private String id;
private String name;
private int age;
public Student(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public Student() {}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String toString() {
return 'ID: ' + id + ', Name: ' + name + ', Age: ' + age;
}
}
import java.util.HashMap;
public class HashMapTest {
public HashMapTest() {
HashMap<String, Student> students = new HashMap<>();
students.put('17H002', new Student('17H002', '孙悟空', 2000));
students.put('17H001', new Student('17H001', '唐僧', 40));
students.put('17H003', new Student('17H003', '猪八戒', 1000));
students.put('17H004', new Student('17H004', '沙僧', 900));
System.out.println(students.get('17H003'));
System.out.println('All Students:');
for (Student s : students.values()) {
System.out.println(s);
}
students.remove('17H001');
Student[] studentArray = students.values().toArray(new Student[0]);
System.out.println('Student Array:');
for (Student s : studentArray) {
System.out.println(s);
}
}
public static void main(String[] args) {
HashMapTest test = new HashMapTest();
}
}
原文地址: https://www.cveoy.top/t/topic/ojPb 著作权归作者所有。请勿转载和采集!