哈希图不保存条目



我的问题是,我正在尝试制作一个资源加载器,将过去的纹理保存到 HashMap 中,并以它们的位置作为键。当它在包外加载图像时,它可以完美运行,但是当它尝试加载内部图像时,它就是不会保存。

这是我的资源加载器代码

public Map<String,BufferedImage> loads = new HashMap<String,BufferedImage>();
public BufferedImage loadImage(String imagePath){
    BufferedImage temp = new BufferedImage(9, 16, BufferedImage.TYPE_INT_RGB);
    String location = imagePath.replaceAll("[.]", "/");
    location += ".png";
    //internal
    if(location.startsWith("CLASS_")){
        if(loads.get(location) != null){
            System.out.println("OLD");
            return loads.get(location);
        }else{
            location = location.replaceAll("CLASS_", "");
            try{
                temp = ImageIO.read(this.getClass().getClassLoader().getResource("net/minegeek360/platformer/assets/"+location));
                loads.put(location, temp);
            }catch(Exception e){System.err.println("CANT LOAD IMAGE");}
            System.out.println("NEW | "+temp);
        }
    //external
    }else{
        try{
            if(loads.get(location) != null){
                //System.out.println("LOADED ORIGIONAL IMAGE");
                return loads.get(location);
            }else{
                temp = ImageIO.read(new File("assets/textures/"+location));
                //System.out.println("LOADED NEW IMAGE");
            }
        }catch(Exception e){ e.printStackTrace(); }
        loads.put(location, temp);
    }
    return temp;
}

正如我所说,外部加载工作得很好,问题只是内部加载。它正确加载了所有图像,所以我知道缓冲图像不是问题,这就是为什么我认为它是哈希图。

将数据放入地图时,前缀"CLASS_"将从用作键的位置中删除。

但是,从地图查询数据时,前缀仍然存在。

您能否为内部部分尝试此代码并提供控制台的输出?

if(location.startsWith("CLASS_")){
    location = location.replaceFirst("CLASS_", "");
    if(loads.get(location) != null){
        System.out.println("OLD");
        return loads.get(location);
    } else {
        try{
            temp = ImageIO.read(this.getClass().getClassLoader().getResource("net/minegeek360/platformer/assets/"+location));
            System.out.println("Loading image, current size: " + loads.size());
            loads.put(location, temp);
            System.out.println("Image loaded,  new size:     " + loads.size());
        }catch(Exception e){System.err.println("CANT LOAD IMAGE");}
        System.out.println("NEW | "+temp);
    }
}

负载永远不会添加任何东西!即使它在我的代码中,它也什么都不做!

怀疑。

您可以检查内部加载的图像,如下所示:

if(location.startsWith("CLASS_")){
    if(loads.get(location) != null){

如果你没有找到一个,那么你像这样加载它:

        location = location.replaceAll("CLASS_", "");
        try{
            temp = ImageIO.read(this.getClass().getClassLoader().getResource("net/minegeek360/platformer/assets/"+location));
            loads.put(location, temp);

您当然会存储图像,但是对以前加载的内部图像的测试永远不会成功,因为您使用与以后尝试用于查找它们的键不同的键(删除了"CLASS_"的所有外观)来存储它们。

问题是我有多个同一个加载器的实例。所以我只是让我的文件只访问一个实例。

最新更新