使用HashMap进行通用子类类型转换

时间:2018-03-17 11:27:38

标签: java generics subclass superclass

好的,我有一个超类 Profile 和两个子类 UserProfile & MovieProfile ,它扩展了个人资料

我有一个CSV格式的userprofiles和movieprofiles文件,并且想要导入这些文件,并且这些格式的信息是相同的,因此导入用户配置文件的HashMap的代码和Movieprofiles的HashMap是令人兴奋的同样,除了我需要指定它是哪种类型的配置文件。

我目前尝试过类似的内容:

public <T> HashMap<Integer, T> importProfileList(String filePath, int totalGenomes, int totalGenres){
    CSV_Reader CSVR = new CSV_Reader(filePath);
    HashMap<Integer, T> profileHashMap = new HashMap<>();

    for (ArrayList<String> readLine : CSVR){
        Profile tempProfile = new Profile(-1, totalGenomes, totalGenres);
        tempProfile.importProfile(readLine, totalGenomes, totalGenres);

        @SuppressWarnings("unchecked")
        T profile = (T) tempProfile;

        profileHashMap.put(tempProfile.getID(), profile);
    }

    return profileHashMap;
}

但是当我尝试在main中运行该函数时,我只是得到一个错误,并尝试访问这些元素。

“java.lang.ClassCastException:Profiles.Profile无法强制转换为Profiles.UserProfile”

我的代码生成 UserProfile HashMap:

public HashMap<Integer, UserProfile> importUserProfiles(String filePath, int totalGenomes, int totalGenres){
    CSV_Reader CSVR = new CSV_Reader(filePath);
    HashMap<Integer, UserProfile> profileHashMap = new HashMap<>();

    for (ArrayList<String> readLine : CSVR){
        UserProfile tempProfile = new UserProfile(-1, totalGenomes, totalGenres);
        tempProfile.importProfile(readLine, totalGenomes, totalGenres);

        profileHashMap.put(tempProfile.getID(), tempProfile);
    }

    return profileHashMap;
}

要生成 MovieProfile HashMap,您只需在上面的代码中使用 MovieProfile 切换每个 UserProfile

上面的代码放在名为 ProfileGenerator 的第三个对象中。

所以我的问题是:

如何为我的子类使用相同的代码块,可能还有泛型?所以我的程序中不需要“复制粘贴代码”?

0 个答案:

没有答案