繁体   English   中英

使用地图不会导致NPE

[英]use of Map doesn't cause NPE

考虑一下:

public class Model{
    private Map<Vector, Vector> vertices;

    public Model(Vector v){
        vertices.put(v, v);
    }
}

我期待NPE,因为顶点尚未初始化。 至少我期待一个错误,因为Map是抽象的并且我正在处理一个对象。 有人可以照亮这里吗?

编辑:

public class World{
    public static void init(){
        Model cube = new Model(someVector);
    }
}

我有一个包含main()的Main类; 在main()中,我正在调用World.init();

该代码经过简化以提高可读性。
编辑1:

public class Model extends Positionable{
    public static Map<String, Model> map = new HashMap<>();
    private Map<Vector3f, Vector3f> vertsAndNormals;
    private Set<Face> faces;

    public Model(String name_, Map<Vector3f, Vector3f> vertsAndNormals_){
        super(); // \!/ passing `this`; may not have been entirely initialized
        vertsAndNormals = new HashMap<>(vertsAndNormals_);
        map.put(name_, this);
        }
    public Model(String name_, Set<Vector3f> vertices_){
        super(); // \!/ passing `this`; may not have been entirely initialized

        for(Vector3f vertex : vertices_)
            vertsAndNormals.put(vertex, new Vector3f(0, 0, 0)); // \!/ why does this NOT cause an NPE?

        map.put(name_, this);
        }
    public Model(String name_){
        this(name_, new HashMap<Vector3f, Vector3f>());
        }
    }

我打电话给的地方:

public class World{
    public static Set<Model> modelsInWorld = new HashSet<>();

    public static void init(){
        Model cube = new Model("gugu");
        }
    }

在main()中:

World.init();  

编辑2:

public abstract class Positionable{
    public static Set<Positionable> set = new HashSet<>(); 

    public float x = 0;
    public float y = 0;
    public float z = 0;
    public float xRol = 0;
    public float yPit = 0;
    public float zYaw = 0;

    public Positionable(){
        set.add(this);
        }
}

您实际上并不是在调用包含您所关注的行的构造函数。 您调用采用String的构造函数,该构造函数转发到采用StringMap的构造函数。 采用Set的构造函数将在运行时导致NPE。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM