1
public static void main(String[] args) {
    Byte test = 3;
    Byte test2 = 3;
    Byte test3 = 3;
    
    Byte[] arr = { test , test2, test3};
    
    for(int i =0; i<arr.length; i++) {
        System.out.println(" test"+i+" " + arr[i] );
    }
    test = 1;
    test2 = 2;
    test3 = 4;
    
    System.out.println(" test " + test);
    System.out.println(" test2 " + test2);
    System.out.println(" test3 " + test3);
    
    for(int i =0; i<arr.length; i++) {
        System.out.println(" test"+i+" " + arr[i] );
    }
}

By entering byte variables into a byte array, I want to make the values โ€‹โ€‹of the variables change the same when the value of the array changes.

In C, I remember that I changed it using an address, but what method should I use to use it in Java?

2 Answers2

0

Java does noes not allow to bind a variable to another variable but you can create wrapper classes:

public class ByteInArray{
    private byte[] array;
    private int index;
    public ByteInArray(byte[] array, int index){
        this.array=array;
        this.index=index;
    }
    public byte getValue(){
        return array[index];
    }
}

You can then use this class for the arrays:

byte[] arr=new byte[]{1,2,3};
ByteInArray first=new ByteInArray(arr,0);

arr[0]=8;
first.getValue();

See this on how objects (including arrays) are passed.

Another option would be to create a class that represents a mutable byte and use an array of that as sorifiend stated in his answer.

dan1st
  • 12,568
  • 8
  • 34
  • 67
0

If you want to update it using the reference then you could create a custom object that stores the Byte internally:

class CustomObject{
    Byte value;

    CustomObject(Byte value){
        setValue(value);
    }
  
    Byte getValue(){
        return value;
    }
    
    void setValue(Byte value){
        this.value = value;
    }
}

Now you can use your code as normal, just swap Byte to your CustomObject as follows:

CustomObject test = new CustomObject(Byte.parseByte("3"));
CustomObject test2 = new CustomObject(Byte.parseByte("3"));
CustomObject test3 = new CustomObject(Byte.parseByte("3"));

CustomObject[] arr = { test , test2, test3};

for(int i =0; i<arr.length; i++) {
    System.out.println(" test"+i+" " + arr[i].getValue() );
}
test.setValue(Byte.parseByte("1"));
test2.setValue(Byte.parseByte("2"));
test3.setValue(Byte.parseByte("4"));

System.out.println(" test " + test.getValue());
System.out.println(" test2 " + test2.getValue());
System.out.println(" test3 " + test3.getValue());

for(int i =0; i<arr.length; i++) {
    System.out.println(" test"+i+" " + arr[i].getValue() );
}
sorifiend
  • 5,927
  • 1
  • 28
  • 45