开发者

Dependent attributes within a java class

开发者 https://www.devze.com 2023-01-16 06:37 出处:网络
I have a java class as follows: public class Query implements Serializable { static Object[] o= new Object[8];

I have a java class as follows:

public class Query implements Serializable {
    static Object[] o= new Object[8];

    private long oid= (Long) o[0];
    private double[] region= { (Double) o[1],(Double) o[2],(Double) o[3]  };
    private boolean filter= (Boolean) o[4];
    private float[] vel= {(Float) o[5], (Float) o[6]};
    private float[] pos= {(Float) o[7], (Float) o[8]};

    public Query(Object[] b){
        o=b;
    }

Class Query will be an array of objects and I want to establish dependency between Object[] o and oid, region,...

If I change region's value, the corresponding value in object[] will be changed automatically.

Could you suggest me some way to do it efficiently. T开发者_开发知识库hanks!


You need to wrap all primitive/immutable types in a mutable type so that you can just reference it. Using a Javabean is a common approach for this.

public class Data {
    private long id;
    private double[] region;
    private boolean filter;
    private float[] vel;
    private float[] pos;

    // Add or generate c'tors/getters/setters/equals/hashcode/tostring here.
}

So that you can just do

public class Query {
    private Data data;

    public Query(Data data) {
        this.data = data;
    }
}


I would definitely use builder design pattern here. It will ensure type safety in the first place. And you could use primitive types... In your implementation it takes only one error on class client side to receive runtime exception. Does that answer your question?

0

精彩评论

暂无评论...
验证码 换一张
取 消