3
public class Test {
    private Result result;

    public Test(Result res){
        this.result = res;
    }

    public void alter(){
        this.result = Result.FAIL;
    }
}

public enum Result{ PASS, FAIL, MORE};
public Result myResult = Result.PASS;

Test test = new Test(myResult);
test.alter();

In the above example, how would I modify the variable myResult inside the alter method? Since Java is pass by value, the example simply assigns its value to this.result.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
Gorgon
  • 33
  • 1
  • 3

5 Answers5

4

Basically, you can't, because Java is pass-by-value.

The closest you can get to pass-by-reference behavior in Java is to create a "holder" class with a getter and setter; e.g.

public class ResultHolder {
    private Result value;
    public ResultHolder(Result initial) { value = initial; }
    public void setValue(Result newValue) { value = newValue; }
    public Result getValue() { return value; }
}

Then, you could write alter() as:

public void alter(ResultHolder holder, Result newValue) {
    holder.setValue(newValue);
}

Note that this is not real pass-by-reference.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thanks, I considered putting it inside an object but wondered if there was some other way to fudge it. – Gorgon Feb 17 '11 at 15:25
3

You can't modify the actual enum values. They're essentially classes that are named constants. If you want altered behavior inside an enum instance then you don't want an enum ( if you can alter the object then other consumers of the object can't treat it as a constant).

Steve B.
  • 55,454
  • 12
  • 93
  • 132
  • +1 This is the real answer. If you are trying to change an enum argument, then you don't want an enum to begin with. – Andres F. Jan 17 '12 at 01:33
0

Simply put, you can't do it in Java.

mdrg
  • 3,242
  • 2
  • 22
  • 44
0

Since myResult is the class field you can change it when you wish by assigning other value: myResult = Result.MORE;. it does not matter where do you write this code.

AlexR
  • 114,158
  • 16
  • 130
  • 208
0
public class Test {
    private Result result;

    public Test(Result res){
        this.result = res;
    }

    public Result alter(){          // signature changed
        this.result = Result.FAIL;
        return this.result;         // new
    }
}

_

public enum Result{ PASS, FAIL, MORE};
public Result myResult = Result.PASS;

Test test = new Test(myResult);
myResult = test.alter();            // change the value
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268