|
-
Dec 1st, 2005, 02:35 PM
#1
Thread Starter
Frenzied Member
what is java equivalent to this c++ code...
Code:
void swap(int & a, int & b)
{
int temp;
temp = a;
a = b;
b = temp;
}
basically, how do i pass an integer variable by reference so I can change the value of the parameter variables after the function call.
-
Dec 1st, 2005, 04:33 PM
#2
Fanatic Member
Re: what is java equivalent to this c++ code...
There isn't that much difference between C and Java code.
Code:
public void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
-
Dec 1st, 2005, 10:49 PM
#3
Fanatic Member
Re: what is java equivalent to this c++ code...
That's not quite the same, because in that Java the values passed to the function will not be swapped.
The problem is that primative data types in Java (such as int) are not used as pointers, whereas classes are.
I believe there may be a library call, but if not you can wrap the values up as Integers (i.e. instances of the class Integer), pass these and unwrap, but that's a lot of extra code. I think Java 5 might do some of this for you with autoboxing, if you write a thing to swap two Objects.
sql_lall 
-
Dec 2nd, 2005, 03:39 PM
#4
Re: what is java equivalent to this c++ code...
Swapping mostly used in arrays, pass the array "By ref", and the locations of the two vars to be swaped
private void swap(int[] array,int locA,int locB){
int tmp=array[locA];
array[locA]=array[locB];
array[locB]=tmp;
}
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
-
Dec 3rd, 2005, 03:49 AM
#5
Thread Starter
Frenzied Member
Re: what is java equivalent to this c++ code...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|