David
David

Reputation: 89

How to treat `int` like an object in an array

As most of you know, when you make a int[]hold variables of type int, the array is not updated when you change the int variables it is holding due to how primitive data types are copied rather than pointed. Is there any way to make this happen however? Possibly

Integer int[] = new Integer[] {Integer f1...};

I want to be able to make an int[] but when I change the variables it holds elsewhere in the program, they are changed within the int[] as well.

Upvotes: 0

Views: 205

Answers (2)

Andy Thomas
Andy Thomas

Reputation: 86429

A simple approach that works for all types is to use an array that holds 1-element arrays.

int[][] pos = new int[3][1];
int[] x = new int[] { 3 };
int[] y = new int[] { 4 };
int[] z = new int[] { 0 };

pos[0] = x;
pos[1] = y;
pos[2] = z;

x[0] = 42; // Translate in x direction

System.out.println( "x=" + pos[0][0] ); // Prints "42"

However, it is usually better to define a class that provides accessors and mutators with meaningful names.

public class Position {
  private x, y, z;
  public int x() { return x; }
  public setX( int x0 ) { x = x0; }
  ... etc
}

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198163

Absolutely no way with an int[]. You could create your own mutable integer class to do it, or abuse AtomicInteger to do it.

 AtomicInteger[] array = new AtomicInteger[5];
 array[0] = new AtomicInteger(6);
 array[0].set(4);
 System.out.println(array[0].get()); // returns 4

Upvotes: 5

Related Questions