Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to an Integer in Java

Tags:

java

pointers

int

I have a code like this

int a,b;
switch(whatever){
    case 1:
      lots_of_lines_dealing_with_variable_a;
    case 2:
      same_lines_but_dealing_with_variable_b;
}

I thought of doing:

int a,b;
pointer_to_int p;
switch(whatever){
    case 1:
      p=a;
    case 2:
      p=b;
}
lots_of_lines_dealing_with_pointer_p;

It would reduce the code to about half the lines, but Java doesn't allow pointers to integers. So, is there any way to approach this?

Edit: The homework is much bigger than just this method. I need to Create a class called "DoubleList" which contains two linked lists in a single Vector. The integers I talk about are the pointers to the start of the Lists, which I need to move to other positions of the Lists when adding or removing elements to the Lists

like image 943
bluehallu Avatar asked Feb 28 '11 16:02

bluehallu


1 Answers

Maybe I'm missing something, but looks easily solvable to me:

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;
}

If you don't need to modify the variables, then you can leave out the return-value (just use void) and the assignment.

If nothing else needs to call the method, then it should be private (it's a general principle: give as little access as possible, as much as necessary).

like image 163
Joachim Sauer Avatar answered Oct 11 '22 04:10

Joachim Sauer