整数不像真正的对象?

3 java function

首先,我很抱歉我的英语.这不是我的主要语言.

class Car {
    private Integer x;

    public Car(){
        this.x = new Integer(5);
    }

    public Integer getInt(){
        return this.x;
    }

    public static void main(String[] args) {
        Car car = new Car();
        Integer x = car.getInt();
        // Here is what annoying me. I want to change the value of car.x only with getInt()
        x += 4;
        system.out.println(""+car.x);
        //This will print 5, when i want it to print 6.
    }
}
Run Code Online (Sandbox Code Playgroud)

这只是一个概念.我需要为我的项目更改Integer THIS方式的值.这似乎是不可能的,但我可能会错过一些东西.

我的意思是,如果我可以这样做,它可能会非常有用:

Integer x = car.getInt();
x.setValue(9);
Run Code Online (Sandbox Code Playgroud)

这是使用Java的问题.我喜欢Java,但在c ++中我可以随处使用指针.

如果你想知道为什么我需要使用这个方法,那是因为我有这两个函数:

private Rectangle2D.Double rect;
private Vector3D position;
Run Code Online (Sandbox Code Playgroud)

rect.x应该具有相同的价值position.x.然后,每当我调整其中一个值时,我都必须更改它们.这些功能中的每一个都用于不同的方法.我使用rect进行渲染,我使用位置来计算..

非常感谢你!

Ósc*_*pez 7

在Java中,Integer类是不可变的,因此您永远无法更改其中一个实例的值.就像设计一样,Integer可以安全地共享同一个实例.