猿问

如何覆盖它以获得结构化的方式

我正在使用 Maps 集合创建学生管理简单的 java 项目,其中 id 是我的密钥,名称、标记和手机号码。是地图的值。那么如何以结构化的方式打印它。


HashMap<Integer, LinkedHashSet<StudentCinstructor>> st = new HashMap<>();

LinkedHashSet<StudentCinstructor> st2 = new LinkedHashSet<>();


Scanner sc = new Scanner(System.in);

public void add() {

    System.out.println("enter the name of the student");

    String name = sc.nextLine();

    System.out.println("enter the marks of the student");

    double marks = sc.nextDouble();

    System.out.println("enter the mobile number of the student");

    long mobile_no = sc.nextLong();

    st2.add(new StudentCinstructor(name, marks, mobile_no));

    System.out.println("enter the unique id of the student");

    int id = sc.nextInt();

    st.put(id, st2);

当我尝试在主方法中打印自定义类时,它给了我一个带有哈希码的地址。“HashmapDemo.MethodsForManagement@3d4eac69”


慕森王
浏览 191回答 2
2回答

蓝山帝景

两个备注:1-当您尝试打印对象StudentCinstructor时,如果没有专门的toString()方法,您将无法获得结构良好的输出。因此,您需要做的是toString()为您的类编写一个方法,然后您可以打印到控制台。例子 :public&nbsp;static&nbsp;String&nbsp;toString()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;"Customize&nbsp;here&nbsp;+&nbsp;Put&nbsp;this&nbsp;method&nbsp;inside&nbsp;your&nbsp;class"; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}2-我不明白您为什么要使用LinkedHashSet存储StudentCinstructor对象然后将此 HashSet 存储在地图中,而不是创建StudentCinstructor对象并将其直接存储在地图中,如果所有学生都有唯一的 id。如 :HashMap<Integer, StudentCinstructor> st = new HashMap<>();

猛跑小猪

查看您的打印输出“HashmapDemo.MethodsForManagement@3d4eac69”,您似乎正在打印 class 的对象HashmapDemo.MethodsForManagement。如果要打印 的对象StudentCinstructor,则需要将该对象传递给 print 方法,例如System.out.println(student);.你需要重写类中的toString()方法StudentCinstructor。(即把下面的代码放在StudentCinstructor课堂上。)( name,marks并且mobile_no在下面的代码中是StudentCinstructor类中的字段。)&nbsp; @Override&nbsp; public String toString()&nbsp; {&nbsp; &nbsp; return "Name=" + name + ", Marks=" + marks + ", Mobile number=" + mobile_no;&nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答