Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer doesn't act like a real Object?

Tags:

java

function

First, I am sorry for my English. It is not my main language.

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.
    }
}

This is only a concept. I need to change the value of an Integer THIS way for my project. It seems to be impossible, but i may miss something.

What I mean is that it could be very helpful if i could do something like this:

Integer x = car.getInt();
x.setValue(9);

That's the problem of using Java. I love Java, but in c++ I could just use the pointer everywhere.

If you wonder why I ever need to use this method, it is because that I have these 2 functions:

private Rectangle2D.Double rect;
private Vector3D position;

rect.x should have the same value as position.x. Then, every time I adjust one of these values, I have to change them both. Each of these functions is used for different methods. I use the rect to render and I use the position to calculate..

Thank you very much!


1 Answers

In Java the Integer class is immutable, so you'll never be able to change the value of one of its instances. It's like that by design, so many instances of the same Integer can be shared safely.

like image 128
Óscar López Avatar answered Feb 05 '26 14:02

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!