简体   繁体   中英

Return Two Arraylists or Use Two Different Methods

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

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.

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.

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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM