【问题标题】:how to override this to get structured manner如何覆盖它以获得结构化的方式
【发布时间】:2019-06-13 06:05:07
【问题描述】:

我正在使用 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"

【问题讨论】:

  • edit您的问题包括minimal reproducible example。另请查看 Object.toString()System.out.println(Object) 的文档以了解您获得的输出。
  • 单个id有多个值吗
  • 不清楚为什么您使用StudentCinstructorsets 作为地图的值,而不是单独的StudentCinstructor 对象。由于地图是通过所提供的add() 方法填充的,因此在地图中用作值的所有集合都不会只有一个元素。

标签: java hashmap linkedhashset


【解决方案1】:

两句话:

1- 当您尝试打印对象StudentCinstructor 时,如果没有专用的toString() 方法,您将无法获得结构良好的输出。因此,您需要为您的班级编写一个toString() 方法,然后您可以打印到控制台。 示例:

public static String toString() {
     return "Customize here + Put this method inside your class";
}

2- 我不明白您为什么要使用 LinkedHashSet 来存储 StudentCinstructor 对象,然后将此 HashSet 存储在地图中,而不是创建 StudentCinstructor 对象并将其直接存储在地图中(如果所有学生)有一个唯一的 id。 如:

HashMap&lt;Integer, StudentCinstructor&gt; st = new HashMap&lt;&gt;();

【讨论】:

  • 谢谢。我是java初学者。我已经直接将它存储在地图中。担心的是我正在接受用户的输入,我想以结构化的方式打印它。所以我需要覆盖 to 字符串.....
  • 您需要将toString() 方法放在StudentCinstructor 类中。如果您查看上面@Prasad 的答案,则有一个示例实现。您可以复制该代码并将其放入您的班级。然后,当您打印出地图中的对象时,它们将以结构化的方式打印出来。
【解决方案2】:

查看您的打印输出“HashmapDemo.MethodsForManagement@3d4eac69”,您似乎正在打印HashmapDemo.MethodsForManagement 类的对象。如果要打印StudentCinstructor 的对象,则需要将该对象传递给像System.out.println(student); 这样的打印方法。

而且你需要重写StudentCinstructor 类中的toString() 方法。 (即把下面的代码放在StudentCinstructor 类中。)

(下面代码中的namemarksmobile_noStudentCinstructor类中的字段。)

  @Override
  public String toString()
  {
    return "Name=" + name + ", Marks=" + marks + ", Mobile number=" + mobile_no;
  }

【讨论】:

    猜你喜欢
    • 2018-09-17
    • 2015-05-31
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多