我目前正在编写此代码,我想将 ID 传递给成员函数以获取对象。
public class Car {
private int _ID;
private String name;
private String model;
Car(int _id, String name, String model){
this._ID = _id;
this.name = name;
this.model = model;
}
....
public static Car getCar(int _id){
Car mCar;
//TODO: Algo to get car
return mCar;
}
}
有什么办法可以通过这种方式获取对象吗?
感谢任何帮助! 谢谢!
最佳答案
您需要按键保存对象的Map
。这是一种方法:
public class Car {
private int _ID;
private String name;
private String model;
Car(int _id, String name, String model){
this._ID = _id;
this.name = name;
this.model = model;
carsById.put(_id, this); // <-- add to map
}
....
private static Map<Integer, Car> carsById = new HashMap<>();
public static Car getCar(int _id){
return carsById.get(_id);
}
}
关于java - 如何从类对象的成员变量中获取类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30749196/