首页 > java 中集合

java 中集合

这是一个学生类:里面包含id和name属性

  public class Student {
    
        public String id;
        
        public String name;
        
        public Set<Course> courses;
    
        public Student(String id, String name) {
            this.id = id;
            this.name = name;
            this.courses = new HashSet<Course>();
        }
    } 

这是用一个map(hashmap实现)来存放学生的ID和name的类:


 public class MapTest {
        //用来承装学生类型对象
       public Map<String, Student> students;
       //在构造器中初始化students属性
        public MapTest() {
            this.students = new HashMap<String, Student>();
        }

问题来了:定义students时用了泛型,泛型里面有个Student,为什么数据类型可以定义为Student,我是这样理解的,java中偏向于吧数据类型封装为类,然后直接用类来表示数据类型,比如integer,Long等等,好,继续看代码

这是往hashmap中添加学生的名字和id的代码:

 /** 测试添加:输入学生ID,判断是否被占用 若未被占用,则输入姓名,创建新学生对象,并且 添加到students中
 */
public void testPut() {
    // 创建一个Scanner对象,用来获取输入的学生ID和姓名
    Scanner console = new Scanner(System.in);
    int i = 0;
    while (i < 3) {
        System.out.println("请输入学生ID:");
        String ID = console.next();
        // 判断该ID是否被占用
        Student st = students.get(ID);
        if (st == null) {
            // 提示输入学生姓名
            System.out.println("请输入学生姓名:");
            String name = console.next();
            // 创建新的学生对象
            Student newStudent = new Student(ID, name);
            // 通过调用students的put方法,添加ID-学生映射
            students.put(ID, newStudent);
            System.out.println("成功添加学生:" + students.get(ID).name);
            i++;
        } else {
            System.out.println("该学生ID已被占用!");
            continue;
        }
    }
}

问题继续:上述代码中

   // 通过调用students的put方法,添加ID-学生映射
     students.put(ID, newStudent);

这里我就不能理解了,添加的newstudent不是对象吗?这里在定义中需要的不是String类型的名字吗?为什么可以这样,关键是运行结果就是MAP(ID,NAME),也就是在map中添加了id和name


所以问题是?

public Map<String, Student> students;
你定义的String-Student对,又问为什么可以这样?


看了题主与一楼的评论和回复,补充一点,类本身也是一种数据类型啊,只是不叫基本数据类型。同意一楼观点,题主定义的是Map<String,Student>,代码那样子写自然是顺理成章咯


你定义了Map来存放Student,Map是键-值存放类型的,即<key,value>,你定义了key是String类型的,value是Student类型的,所以你后面的代码相对应会这样插入相应的类型,而你说的最后得到了name,是不是说控制台打印了name?如果是的话,那是因为你用了Map.get(key)获得了一个Student类型的value,然后又访问了name属性,有错误欢迎指正~


是的,正如一楼所说的,你是这样定义的:

public class MapTest {
        //用来承装学生类型对象
       public Map<String, Student> students;
       //在构造器中初始化students属性
        public MapTest() {
            this.students = new HashMap<String, Student>();
        }

当然使用students.put(ID, newStudent);来存放值了。你的ID是String类型对应key,newStudent是Student类型的,对应你定义的值。

【热门文章】
【热门文章】