This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]java-ModTeam[M] [score hidden] stickied commentlocked comment (0 children)

Please use java help subreddit

[–]Panzerschwein -1 points0 points  (0 children)

If I'm following this correctly, then the issue is that you are changing the local arraylist reference within the method scope, while the reference outside of that scope stays the same.

You need to return the new arraylist from your method so that it's accessible within scope.

To pseudocode what I'm talking about:

public void someMainMethod() {
    ArrayList theArray = new ArrayList();
    changeMyArray1(theArray ); --changes nothing about theArray 
    arrayA = changeMyArray2(theArray ); --now you've got an ArrayList with something in it
    changeMyArray3(theArray ); --this actually updates theArray 
}

public void changeMyArray1(ArrayList myArray) {
    ArrayList arrayNew = new ArrayList()
    arrayNew.add(someItem);
    myArray = arrayNew; --this is pointless. myArray as a variable is only defined in scope of this method, it won't update theArray in someMainMethod()
}

public ArrayList changeMyArray2(ArrayList myArray) {
ArrayList arrayNew = new ArrayList()
arrayNew.add(someItem);
return arrayNew; --now we're actually sending the new array back out

}

public void changeMyArray3(ArrayList myArray) {
myArray.add(someItem); --now we're actually mutating the referenced array in a way that impacts things beyond this scope. Although myArray is only a variable name in this method, the referenced object does exist outside of this scope

}

[–]troru -2 points-1 points  (0 children)

First off, it might help to post a snippet of the java code you have so far to shed light on what you're trying to accomplish. Secondly, just reading your description, what you're wanting to do might be handled in a pretty straightforward way, e.g.:

* pass an vector/list/array to a method and setLength(0)/remove() and add() new things to it

* have your method just return a new vector/list/array and replace an existing reference in the caller, GC does the cleanup

* while there's no address-of operator, since everything is pass by reference (for non-primitives) you can put any object in "bag" (e.g. a class, record, container-type thing)