指向Java中的整数的指针

blu*_*llu 11 java int pointers

我有这样的代码

int a,b;
switch(whatever){
    case 1:
      lots_of_lines_dealing_with_variable_a;
    case 2:
      same_lines_but_dealing_with_variable_b;
}
Run Code Online (Sandbox Code Playgroud)

我想到了:

int a,b;
pointer_to_int p;
switch(whatever){
    case 1:
      p=a;
    case 2:
      p=b;
}
lots_of_lines_dealing_with_pointer_p;
Run Code Online (Sandbox Code Playgroud)

它会将代码减少到大约一半的行,但Java不允许指向整数.那么,有什么方法可以解决这个问题吗?

编辑:作业比这个方法大得多.我需要创建一个名为"DoubleList"的类,它在一个Vector中包含两个链接列表.我所谈到的整数是指向列表开头的指针,在向列表中添加或删除元素时,我需要将其移动到列表的其他位置

Joa*_*uer 19

也许我错过了什么,但看起来很容易解决我:

int a,b;

switch(whatever) {
  case 1:
    a = manipulateValue(a);
    break;
  case 2:
    b = manipulateValue(b);
    break;
}

int manipulateValue(int v) {
  // lots of lines dealing with variable v
  return v;
}
Run Code Online (Sandbox Code Playgroud)

如果您不需要修改变量,那么您可以省略返回值(仅使用void)和赋值.

如果没有其他任何东西需要调用该方法,那么它应该是private(这是一般原则:尽可能少地访问,尽可能多).


Teo*_*zon 5

你可以尝试使用拳击.

public class IntBoxer {
    public IntBoxer() {
    }
    public IntBoxer(int startValue) {
        this.value = startValue;
    }
    public int value;
}
IntBoxer a = new IntBoxer();
IntBoxer b = new IntBoxer();
IntBoxer p;
Switch(whatever){
    case 1:
      p=a;
      break;
    case 2:
      p=b;
      break;
}
lots_of_lines_dealing_with_pointer_p.value;
Run Code Online (Sandbox Code Playgroud)

  • @ubadub Integer(和其他内置的原始框类)是不可变的。当您只希望能够在泛型中使用它时就很好了,但是如果您希望能够从多个位置对值进行变异,那将不是一个好选择。就是说,还有一个“ AtomicInteger”类,可以在线程之间安全地共享它(但速度较慢,因为它必须确保正确的多线程行为)。 (2认同)