🙂
The problem I’m having: It’s the very simplified version of what I’m trying to do, as I actually need to recount a large array of colors (taken from Color Object), and need to sort them, and remove and count duplicates in 2 arrays. (Or whatever data model I should use, I chose 2 arrays).
The problem I’v having is that I cant re-reference the array within a method the way it stays there afterwards.
public class Algos2 {
private int[] b1 = null;
public void relink(int[] a1, int[] a2) {
a2 = a1;
}
public Algos2() {
int[] a1 = { 0, 5, 5, 5, 3, 3, 0, 0, 1, 2, 1, 5};
relink(a1, b1);
System.out.println("a1 " + a1); // whatever, working
System.out.println("b1 " + b1); // still null
}
public static void main(String[] args) {
new Algos2();
}
}
b1should return the same pointer as a1 afterwards. And I need to do it within a method. :/
Edit: I also can’t do it directly, returning an array by a method. So no: public int[] relink(int[] a1) {return a1;} as I also would neeed to call that from within another method, which also results in null
This doesn’t work because Java passes arguments by value (even if that value is a reference, such as a reference to an array). It can’t change the value of
b1withinrelink– because all it receives is a copy of the value ofb1. (Well, it could assign directly tob1in this case because it’s an instance method andb1is an instance variable, but I suspect that’s just a coincidence which may not be valid in your real code.)If you want the two variables to refer to the same array, why don’t you just use the assignment operator within the calling method?
Alternatively if you have other work to do, you could potentially make the method return a reference to the appropriate array:
It’s hard to know exactly what’s most appropriate as you haven’t really told us about what you’re trying to do. If you want to be able to remove elements, then arrays may very well be the wrong data structure to use, precisely because you can’t remove elements from them. Have you considered using a
List<E>implementation instead, such asArrayList<E>?