【问题标题】:How do I implement attributes from a hashMap when creating an object for a subclass?为子类创建对象时,如何从 hashMap 实现属性?
【发布时间】:2021-01-09 21:12:15
【问题描述】:

我试图做的基本上是迭代我的流派并将我的 hashMap 用作查找表,然后在创建对象时选择流派。我不知道接下来我需要做什么,因为当我已经有了一个新的构造函数时,它总是给我创建一个新的构造函数的错误。

import java.util.HashMap;
import java.util.Scanner;

public class disc {
   private String title;
   private String releaseDate;
   HashMap<Integer, String> genre = new HashMap<Integer, String>();
   Scanner mainInput = new Scanner(System.in);

    public disc(String releaseDate, String title, HashMap<Integer, String> genre) {
        this.title = title;
        this.releaseDate = releaseDate;
        this.genre = genre;
        this.genre.put(1, "Horror");
        this.genre.put(2, "Action");
        this.genre.put(3, "Hip-Hop");
        this.genre.put(4, "Pop");
        this.genre.put(5, "Jazz");
        this.genre.put(6, "Thriller");
    }

子类:

import java.util.HashMap;

public class game extends disc{
    private int PEGIRating;
    private String Platform;
   public game(int PEGIRating, String Platform, String title, String releaseDate, HashMap<Integer, String> genre){
        super(releaseDate, title, genre);
        this.PEGIRating = PEGIRating;
        this.Platform = Platform;

        game g = new game(18,"PS5","Evil Within","Feb 2018",1);

    }
}

【问题讨论】:

    标签: java hashmap subclass superclass


    【解决方案1】:

    如上所述,您正在游戏构造函数中初始化游戏对象,这将编译但可能会导致运行时问题。

    要补充一点,您将 int 数据类型传递给游戏构造函数的最后一个参数,而不是像构造函数签名中指定的那样传递 HashMap。要么创建一个构造函数,它采用确切的参数列表,但将 int 作为最后一个数据类型,或者将 HashMap 作为最后一个参数传递。

    【讨论】:

    • 谢谢 Mamod,我会尝试将 HashMap 作为最后一个参数传递,我不知道它的语法,但我会查一下。
    • HashMap hashMap = new HashMap(); hashMap.put(1, "blah blah");游戏 g = new game(18,"PS5","Evil Within","Feb 2018", hashMap);
    【解决方案2】:

    您正在尝试在 game() 构造函数中初始化游戏对象...

    public game(int PEGIRating, String Platform, String title, String releaseDate, HashMap<Integer, String> genre){
        super(releaseDate, title, genre);
        this.PEGIRating = PEGIRating;
        this.Platform = Platform;
    
        // >>>  game g = new game(18,"PS5","Evil Within","Feb 2018",1); <<<<
    
    }
    

    【讨论】:

    • 哦,我想我需要一个方法。谢谢
    猜你喜欢
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多