简体   繁体   English

填充嵌套的HashMap

[英]Populate Nested HashMaps

I have a HashMap wich contains a HashMap , and this second HashMap contains another HashMap : 我有一个HashMap其中包含一个HashMap ,而第二个HashMap包含另一个HashMap

public static final Map<String, Map<String, Map<String, Boolean>>> questionnaireData;

I want my HashMap to be static and final and contains data, so I did the following : 我希望我的HashMapstatic并且是final并且包含数据,所以我做了以下工作:

public static final Map<String, Map<String, Map<String, Boolean>>> questionnaireData;
    static {
        Map<String, Map<String, Map<String, Boolean>>> data = new HashMap<>();
        data.put(
            "Architecture des ordinateurs",
            new HashMap<String, Map<String, Boolean>>() {{
                put(
                    "1. La partie du processeur spécialisée pour les calculs est :",
                    new HashMap<String, Boolean>() {{
                        put("L’unité mathématique", false);
                        put("Les Registres", false);
                        put("L’unité arithmétique et logiqueue et logique", true);
                        put("UCC", false);
                    }}
                );
                put(
                        "2. Dans un ordinateur, les données sont présentées par un signal électrique de la forme :",
                        new HashMap<String, Boolean>() {{
                            put("Analogique", false);
                            put("Numérique", true);
                            put("Alphanumérique", false);
                            put("Alphabétique", false);
                        }}
                    );
                put(
                        "3. Les différents éléments d’un ordinateur (mémoire, processeur, périphériques…) sont reliés entre eux par des:",
                        new HashMap<String, Boolean>() {{
                            put("Fils/câbles", true);
                            put("Registres", false);
                            put("Cartes d’extensions", false);
                            put("Bus", false);
                        }}
                    );
            }}
        );
        data.put(
                "Bureautique",
                new HashMap<String, Map<String, Boolean>>() {{
                    put(
                        "1. Quelles sont les fonctions d’un logiciel de traitement de texte ?",
                        new HashMap<String, Boolean>() {{
                            put("Mise en page d’un texte", true);
                            put("Compilation d’un texte", false);
                            put("Présentation d’un texte sous forme de diaporama  ", false);
                            put("Edition d’un texte", true);
                        }}
                    );
                    put(
                            "2. Insérer des lignes supplémentaires dans un tableau Word :",
                            new HashMap<String, Boolean>() {{
                                put("Cela n'est pas possible et il faut calculer dès le départ le nombre de lignes qui seront nécessaires.", false);
                                put("Peut se faire à n'importe quel moment en allant dans la dernière cellule du tableau et en appuyant sur la touche Espace.", false);
                                put("Peut se faire à n'importe quel moment en utilisant le menu Tableau - Insérer Lignes.", true);
                                put("Peut se faire à n'importe quel moment en allant dans la dernière cellule du tableau et en appuyant sur la touche Entrer.", false);
                            }}
                        );
                    put(
                            "3. Qu’est ce qu’une cellule :",
                            new HashMap<String, Boolean>() {{
                                put("La cellule est une colonne.", false);
                                put("La cellule est une ligne.", false);
                                put("Aucune des deux réponses.", true);
                            }}
                        );
                }}
            );
        questionnaireData = Collections.unmodifiableMap(data);
    }

I heard that using anonymous class can make problems, but I can't find any other method than this. 我听说使用匿名类可能会造成问题,但是除此以外我找不到其他方法。

In fact, There is a method where I have to declare and populate a HashMap and use it as an argument for the parent HashMap , but in my case I'll end up with hundreds of declarations. 实际上,有一种方法必须声明并填充HashMap并将其用作父HashMap的参数,但是在我的情况下,我将得到数百个声明。

What do you think about my code? 您如何看待我的代码? and if there is some better method, please let me know. 如果有更好的方法,请告诉我。

Since you asked for an example, here we go. 既然您想举一个例子,那么我们开始吧。

Topic: 话题:

package com.answer.stack.overflow.questionnaire;

import java.util.Set;
import java.util.TreeSet;

public class Topic {
  private String title;

  private Set<Question> questions = new TreeSet<Question>();

  public Topic(String title) {
    this.title = title;
  }

  public String getTitle() {
    return title;
  }

  public void addQuestion(Question question) {
    questions.add(question);
  }

  public Set<Question> getQuestions() {
    return questions;
  }

  @Override
  public String toString() {
    String text = "Topic is ... " + title + "\n";

    for (Question question : questions) {
      text += question.toString() + "\n";
    }

    return text;
  }
}

Question: 题:

package com.answer.stack.overflow.questionnaire;

public class Question implements Comparable<Question> {
  private String text;
  private String code;

  private Answer correctAnswer;

  public Question(String code, String text, String correctAnswerText) {
    this.code = code;
    this.text = text;
    this.correctAnswer = new Answer(code, correctAnswerText);
  }

  public String getText() {
    return text;
  }

  public String getCode() {
    return code;
  }

  public boolean isCorrect(String answer) {
    return correctAnswer.getText().equalsIgnoreCase(answer);
  }

  @Override
  public int compareTo(Question o) {
    return code.compareToIgnoreCase(o.code);
  }

  @Override
  public String toString() {
    return code + ": " + text + " (" + correctAnswer.getText() + ")";
  }
}

Answer: 回答:

package com.answer.stack.overflow.questionnaire;

public class Answer {
    private String code;
    private String text;

    public Answer(String code, String text) {
        this.code = code;
        this.text = text;
    }

    public String getText() {
        return text;
    }

    @Override
    public String toString() {
        return code + ": " + text;
    }
}

Questionnaire: 问卷调查:

package com.answer.stack.overflow.questionnaire;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Questionnaire {
  private List<Topic> topics = new ArrayList<Topic>();

  public void addTopic(Topic topic) {
    topics.add(topic);
  }

  public void checkAnswers(Map<String, String> answers) {
    for (Topic topic : topics) {
      for (Question question : topic.getQuestions()) {
        String code = question.getCode();
        String answerText = answers.get(code);

        if (answerText == null) {
          System.out.println("Answer not provided for question " + code + ".");
        } else if (!question.isCorrect(answerText)) {
          System.out.println("\"" + answerText + "\" is an incorrect answer for question " + code + ".");
        } else {
          System.out.println("Question " + code + " was answered correctly!");
        }
      }
    }
  }

  @Override
  public String toString() {
    String text = "";

    for (Topic topic : topics) {
      text += topic.toString() + "\n";
    }

    return text;
  }

  public static void main(String[] args) {
    Questionnaire questionnaire = new Questionnaire();
    Map<String, String> answers = new HashMap<String, String>();
    Topic topic = new Topic("My attributes");

    topic.addQuestion(new Question("1A", "What is my name?", "Anonymous"));
    topic.addQuestion(new Question("1B", "How tall am I?", "190 cm"));

    questionnaire.addTopic(topic);

    topic = new Topic("Maths");

    topic.addQuestion(new Question("2A", "How much is 1+1?", "2"));
    topic.addQuestion(new Question("2B", "How much is 3/0?", "Not a number"));

    questionnaire.addTopic(topic);

    System.out.println(questionnaire.toString());

    answers.put("1B", "190 cm");
    answers.put("2A", "2");
    answers.put("2B", "infinite?");

    questionnaire.checkAnswers(answers);
  }
}

Output: 输出:

Topic is ... My attributes 主题是...我的属性
1A: What is my name? 1A:我叫什么名字? (Anonymous) (匿名)
1B: How tall am I? 1B:我有多高? (190 cm) (190厘米)

Topic is ... Maths 主题是...数学
2A: How much is 1+1? 2A:1 + 1多少钱? (2) (2)
2B: How much is 3/0? 2B:3/0是多少? (Not a number) (不是数字)

Answer not provided for question 1A. 未提供问题1A的答案。
Question 1B was answered correctly! 问题1B回答正确!
Question 2A was answered correctly! 问题2A回答正确!
"infinite?" “无穷?” is an incorrect answer for question 2B. 是对问题2B的不正确答案。

Note that you should read all the questions from a file, like qqilihq suggested, instead of hard coding them into your program. 请注意,您应该从文件中读取所有问题,如建议的qqilihq ,而不是将其硬编码到程序中。

Also this isn't an optimized version by all means. 同样,这绝对不是一个优化的版本。 Point was to just demonstrate how to solve the same problem with custom classes. 重点是演示如何使用自定义类解决相同的问题。 You may want to look into visitor pattern for checking answers in an elegant and easy way and subclassing different types of answers for instance. 您可能希望研究访问者模式,以一种简便的方式检查答案并将其归类为不同类型的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM