首页 > 解决方案 > 读取文件并将其内容转换为 HashMap 时出现“警告:[未选中] 未选中的转换”

问题描述

我正在阅读一个我以前写为 HashMap<String,String> 的文件。现在,我必须再读一遍,但它给了我“警告:[unchecked] unchecked conversion”,而且它没有编译。

导致错误的代码行:

HashMap<String,String> map_stage = Utils.readObject(staging_area, HashMap.class);

staging_area 是一个文件 obj,工作正常。左侧的 HashMap<String,String> 类型和右侧的 HashMap.class 之间的警告令人感叹

警告:

  required: HashMap<String,String>
  found:    HashMap
Repository.java:156: warning: [unchecked] unchecked conversion
            HashMap<String,String> map_stage = Utils.readObject(staging_area, HashMap.class);
                                                               ^

这是 Utils.readObject:

    /** Return an object of type T read from FILE, casting it to EXPECTEDCLASS.
     *  Throws IllegalArgumentException in case of problems. */
    static <T extends Serializable> T readObject(File file,
                                                 Class<T> expectedClass) {
        try {
            ObjectInputStream in =
                new ObjectInputStream(new FileInputStream(file));
            T result = expectedClass.cast(in.readObject());
            in.close();
            return result;
        } catch (IOException | ClassCastException
                 | ClassNotFoundException excp) {
            throw new IllegalArgumentException(excp.getMessage());
        }
    }

^ 这个方法是给我的,所以你可以假设是正确的。

编译器错误:

grader/submit/AGTester.java:90: error: unreported exception IOException; must be caught or declared to be thrown
        Main.main(args);
                 ^
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error

标签: javafilehashmap

解决方案


我们找到了以下解决方法:

parent_commit_map =  (HashMap <String, String>) readObject(parent_commit_file) 

我不会提倡最好的实现,但它解决了问题。谢谢大家的建议!


推荐阅读