I am interested in doing this C code in Java:
// sets n's ith bit from right, i starts from 0
void setBit(int* n, int i){
*n = *n | (1 << i);
}
However, it looks like java can’t pass addresses, so what would be some clean approaches?
I thought of two approaches, but I was wondering if there are better ways to do it?
Approach 1: using an array
// sets n[0]'s ith bit from right, i starts from 0
public void setBit(int[] n, int i){
n[0] = n[0] | (1 << i);
}
Approach 2: using a class
private class Data{
int value;
}
// sets d.value's ith bit from right, i starts from 0
public void setBit(Data d, int i){
d.value = d.value | (1 << i);
}
Nope, no better way to do it…
Unless you’d like to do it the traditional Java way, which is
This is all to say in Java that “modifying arguments to a function” is almost inherently unclean. The clean way is to find some alternative to modifying the arguments.
(Sometimes it’ll be inevitable, in which case your workarounds are the way to go. That said, if you want to write a method
modify(myData), it’s frequently better to add amodify()method tomyData‘s class.)