在不创建新实例的情况下操纵整数对象



我有:

// lets call this Integer reference ABC101
Integer i = new Integer(5);
//j points to i so j has the reference ABC101
Integer j = i;
//creates a new Integer instance for j?
j++;
//I want j++ to edit and return ABC101
System.out.println(i); // 5 not 6

因此,我的目标是通过不同的对象通过相同的参考来操纵I,而无需切换引用。不,不要说:"为什么不只是使用int,或者为什么不直接弄乱我"。这不是这项练习的目的。总有更简单的方法来做事,但这是我应该处理的。最后一个问题...这是否意味着整数对象是不变的?

的确,所有原语(int,boolean,double等)及其各自的包装类都是不可分割的。

不可能使用后启动操作员j++更改i的值。这是因为j++转换为j = j + 1,而分配运算符=表示I和J不再参考同一对象。

您可以做的是使用一系列int(或您喜欢的整数)。然后,您的代码看起来像这样

int i[] = {5};
int j[] = i;
j[0]++;
System.out.println(i[0]); // prints 6

不建议这样做。我认为,您应该使用自己的包装班来进行INT,看起来像这样

public class MutableInt
private int i;
public MutableInt(int i) {
  set(i);
}
public int get() {
  return i;
}
public void set(int i) {
  this.i = i;
}
public void increment() {
  i++;
}
// more stuff if you want to

请注意,您将无法以这种方式使用Autobox,并且没有java.lang.Integer

的缓存

您可以使用AtomicInteger

进行此操作
    AtomicInteger i = new AtomicInteger(5);
    AtomicInteger j = i;
    j.addAndGet(1);
    System.out.println(i); //6
    System.out.println(j); //6

最新更新