我有这样的代码
int a,b;
switch(whatever){
case 1:
lots_of_lines_dealing_with_variable_a;
case 2:
same_lines_but_dealing_with_variable_b;
}
我想这样做:
int a,b;
pointer_to_int p;
switch(whatever){
case 1:
p=a;
case 2:
p=b;
}
lots_of_lines_dealing_with_pointer_p;
它会将代码减少到大约一半的行数,但 Java 不允许指向整数的指针。那么,有什么办法可以解决这个问题吗?
编辑:家庭作业比这个方法要大得多。我需要创建一个名为“DoubleList”的类,它在单个 Vector 中包含两个链表。我说的整数是指向Lists开始的指针,我需要在向Lists添加或删除元素时将其移动到Lists的其他位置
最佳答案
也许我遗漏了什么,但对我来说很容易解决:
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;
}
如果不需要修改变量,则可以省略返回值(只需使用 void
)和赋值。
如果没有别的需要调用该方法,那么它应该是 private
(这是一个一般原则:尽可能少地提供访问权限,尽可能多地提供必要的访问权限)。
关于java - 在 Java 中指向整数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5144691/