H
H
hudrogen2017-04-24 15:53:21
Java
hudrogen, 2017-04-24 15:53:21

How to pass an instance of the Long class by reference?

In the main method, I declare further I pass it as a parameter to the constructor of another class, in which I assign a value to this object
Long l = 0l;

this.l = l;
this.l = 150l;

After these I output the value of l in main-e - it has not changed.
I'm passing an object, not a primitive

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2017-04-24
@hudrogen

You are a little confusing ramsey God's gift and scrambled eggs changing an object by reference and changing a link. Specifically, in your case, you create a new object and assign a link to it.
Also, Long is immutable. Either way, you wouldn't be able to do anything.
If you really need to change the contents of a certain field in main from a class method, you will have to use self-written holders.

Tyk!
class Test {
    public static void main(String[] args) {
        LongHolder holder = new LongHolder(0L);
        System.out.println(holder);
        updateValue(holder, 150L);
        System.out.println(holder);
    }

    private static void updateValue(LongHolder holder, Long newValue) {
        holder.setValue(newValue);
    }

    private static class LongHolder{

        private Long value;

        public LongHolder(Long value) {
            this.value = value;
        }

        public Long getValue() {
            return value;
        }

        public void setValue(Long value) {
            this.value = value;
        }

        @Override
        public String toString() {
            return "LongHolder{" +
                    "value=" + value +
                    '}';
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question