Passing by object reference Wrapper for method

3

I've been researching about passing by reference in Java and realized that you can not directly do this. As only object references and array's can be passed by reference I thought about using the Wrapper classes to solve problems where I need to change an integer, for example, that is in main using a method. I did several tests but the change is never done properly. Where am I going wrong? And what would be an alternative way to solve my problem? Home Here is the code that I did for these tests.

public class ReferenciaTeste {
    public static void main (String[] args)
    {
        Integer k = new Integer(1);

        System.out.println(k.toString()); //anterior à passagem

        ReferenciaTeste.muda(k);

        System.out.println(k.toString()); //depois da passagem

    }
}


public static void muda(Integer n)
{
    n = 3;
}

Output:

1
1
    
asked by anonymous 20.11.2015 / 01:40

2 answers

3

What happened

What happens logically after the first assignment is this:

ItdoesnotmatterthatyouusednewInteger(1)orsimply1,theresultisthesame.

Whenyoucalledthemudamethod,whathappensisthis:

Andfinally,whenthesecondassignmentoccurs,wehaveanewvalueforn:

Whenthemudamethodends,thenvariableandthe3valuearediscardedandthestateremainsthesameasthefirstimage.

Whathappenstoanarray

Whenusinganarray,youareactuallyreferencinganobjectthatcontainsmultiplevalues:

Whenyoupassthistothemudamethod,youhavetwovariablespointingtothearray:

Whenchanginganelement,thetwovariablesremainpointingtothesamearray,buttheinternalstateofthearrayisaffected,changingoneofitsvalues.

Finally,afterexecutingthemethod,thekvariableremainsintactandunchanged,however,theinternalstateoftheobjectitreferenceshasbeenaffected:

Using a wrapper object

The DannE response tells you how you can use an object whose internal value can be affected.

I'm not going to draw this because it would be exactly the same sequence using the vector.

In fact, many people use vectors or maps as an easy way to change parameters, but this is not very common or good practice.

Considerations

Immovable objects such as Integer and String and references that can not be affected in methods (such as pointers in C) exist for a very simple reason: keep developers healthy .

I say this because although it leaves the language more restricted, it also avoids numerous problems where values are unexpectedly modified by obscure methods. In a language that claims to be easy and universal, this is a small price to pay.

In addition, the basic solution to this case is extremely simple. Just return the modified object:

public static void main (String[] args) {
    Integer k = 1;
    Integer k1 = incrementa2(k);
    System.out.println(k1); 
}

public static Integer incrementa2(Integer n) {
    return n + 2;
}
    
20.11.2015 / 04:46
3

Explaining your problem in detail:

1 - When you create the object k , you allocate in memory an object that references this Integer . 2 - When you call the muda(Integer n) method, you are declaring a Integer in the muda method . What does that mean? This means that by passing the variable k as a parameter of this method, the two ( k and n ) will be referencing the same object in memory. 3 - The problem is: from the moment you change the value of the n variable, this variable will no longer reference the same object of the variable k , referencing a new object Integer value, in your case% with%. Home In short, any changes you make to the 3 declared within of the Integer method will only have effect on this same method, not influencing the external object that was passed as a parameter.

How to resolve
Create a class called, for example, muda(Integer n) and create an object of type IntegerWrapper , and add its getters and setters. In this way, you will always be using the same object in your changes. An example of what this wrapper might look like:

public class IntegerWrapper {
    private Integer i;

    public void setValue(Integer i) {
        this.i = i;
    }

    public Integer getValue() {
        return i;
    }
}
    
20.11.2015 / 02:49