簡體   English   中英

如何自動將用戶定義的對象存儲到地圖中?

[英]How do I automatically store user defined objects into a map?

我正在創建一個小程序,允許您插入自己的多項選擇問題,並可以通過另一種方法向您詢問這些問題。 所以我用構造函數、一個 toString() 方法和一個可以問我這些問題的方法設置了我的“問題類”。 我現在的問題是我必須以某種方式存儲問題,因為問題參數之一是整數“優先級”,如果您回答正確或錯誤,它就會改變。

我想到了一張地圖,如下所示,但我不知道如何正確設置它,因此它會自動將新創建的問題存儲到這張地圖中。 也許我必須創建另一個方法來做到這一點,但我想找到一種排除調用額外方法的方法。 下面的代碼顯示了我如何在 main 方法和數據字段以及 Question 類的構造函數中創建一個新問題。

所以在這個例子中,我想將問題 number1 保存到 Map 數據庫中。 我不想手動執行此操作。

public static void main(String[] args) {

Question number1 = new Question("What is the right answer?",
            new String[] { "1", "2", "3", "4" }, 3, 1.0);
}

public class Question {

public String question;
public String[] answers;
public int solution;
public double priority;
public static Map<Integer, Question> Database = new TreeMap<Integer,Question>();

public Question(String que, String[] ans, int sol, double prio){
this.question = que;
this.answers = ans;
this.solution = sol;
this.priority = prio;

}

根據您的評論,要自動將其插入地圖,請使用:

public class Question {

   static int keyCount; 

   public Question(String que, String[] ans, int sol, double prio){
      this.question = que;
      this.answers = ans;
      this.solution = sol;
      this.priority = prio;
      Database.put(++keyCount, this);
   }

}

在這里,每次創建新對象時,我們都會在地圖中插入一個條目。

  1. this指的是當前創建的對象。
  2. 靜態變量keyCount用於在每次創建對象時增加鍵的值。

我建議不要將對象添加到構造函數中的 Map 中。 原因之一是單一職責原則。 您的構造函數會做兩件事(初始化一個對象並將其添加到 Map)。 這是一個不好的做法,特別是因為方法的名稱(在您的情況下是構造函數)沒有清楚地說明它的作用。 另一個原因是在構造函數中使用了“this”。 這樣做時應該非常小心,因為它會導致非常難以調試的問題。 原因是:當您仍在構造函數中時,您的對象(即“this”)尚未完全初始化。 因此,您將一個未完全初始化的對象作為參數傳遞給方法。 正如我所說,這可能會導致大問題。

如果你真的需要做所有的事情,你可以在你的類中創建一個靜態方法,如下所示:

   public static addQuestion(String que, String[] ans, int sol, double prio){
      int key = Database.size();
      Database.put(key, new Question (que, ans, sol, prio));
   }

然后你可以這樣稱呼它:

   Question.addQuestion("What is the right answer?",
            new String[] { "1", "2", "3", "4" }, 3, 1.0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM