Understanding Instance Identification from Member Variables

Asked 1 years ago, Updated 1 years ago, 369 views

I want to identify the instance where the variable is stored from the member variable.For example, if you create the following instance, can you identify other member variables from StudentID1 to the instance name sample1 or sample1?

class Student {
    int studentID;
    String name;
    intage;
}
Student sample 1 = new Student (1, "Taro", 14);

java

2022-10-23 16:00

2 Answers

Can I identify other member variables in Sample1?

Wouldn't it be better to manage Student instances with HashMap?

How to use Java|HashMap

If the HashMap key is StudentID and the value is Student instance, the get method can reference the instance from StudentID.Naturally, you must implement getter of member variables in the Student class.


2022-10-23 16:00

HashMap recommends managing Student instances.

How about this one?

Make the constructor private so that you can create an instance only with the factory method.
Ensure that the factory method manages the instance.
Use the getStudent method for instance information.

public class Student {
    Integer studentId;
    String name;
    intage;

    private static Map<Integer, Student>studentMap=new HashMap<>();
    private Student(Integer studentId, String name, age) {
        This.studentId=studentId;
        this.name = name;
        This.age=age;
    }

    public static student factory (Integer studentId, String name, age) {
        Student student = new Student (studentId, name, age);
        studentMap.put(studentId, student);
        return student;
    }
    public static Student getStudent(Integer studentId) threads Exception {
        if(studentMap.containsKey(studentId)){
            return studentMap.get(studentId);
        }
        US>throw new Exception("No instance exists.");
    }

}


2022-10-23 16:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.