Reputation: 99
If I have a method
public ArrayList<String> necessaryChanges(Set<Object> setToCheck ) {
//checks to see whether each element of set is correct by comparing it to something
// and if it needs to be changed its added to an arraylist to be returned to the user
}
I need to return a list with necessary changes which is fine.
But I also want to modify setToCheck with the changes. I know you cant return two objects in a method. What I am asking is what is the most efficient way of doing this.
I know I can create another method in the main class and call it to change the set, but it seems really inefficient.
Is there a better way of doing this.
Thanks
Upvotes: 1
Views: 1011
Reputation: 301
As others have pointed out, Java is pass by reference. So, if you change an object in setToCheck, it will be changed in memory and therefore no need to do anything other than change your object reference. For instance...
public List<String> neccessaryChanges(Set<Object> setToCheck) {
List<String> changeList = new ArrayList<String>();
Iterator<Object> iterator = setToCheck.iterator();
while(iterator.hasNext()) {
Object objectToCheck = iterator.next();
if(objectMustChange) {
//once you change the object here, it will change
//in setToCheck since objectToCheck now equals something
//different and setToCheck still has reference to
//objectToCheck
objectToCheck = new String();
changeList.add((String) objectToCheck);
}
}
return changeList;
}
Upvotes: 1
Reputation: 2618
If you modify the setToCheck
object inside the necessaryChanges
method, the changes will be visible also outside of that method, since in Java everything (primitive types excluded, but it's not your case) is passed as reference.
So basically you don't need to return the setToCheck
object: you can simply still use it after the method call: it is always the same object (inside and outside the method), therefor it will contains the new changes.
Upvotes: 5
Reputation: 3302
By your problem description, you don't need to return
two objects. You can just create and return
an ArrayList
and make alterations to setToCheck
in-place. Since setToCheck
is an object reference, any changes made to the object inside the method will be visible outside.
Upvotes: 1