4

can you give me example how to update values in one object by another object of same type? For example here is my class:

public class MyObj {
   private int id;
   private String name;
   private String phone;
   private String address;

   // some getters and settters ...
}

And I have another class with that stuff:

private ArrayList<MyObj> objectsList; // list of some objects
public MyObj update ( MyObj newObj ) {

    // here I need set new values of properties of newObj to object with same id property in objectsList;
}

Exist some way how to do that without manually setting up all properties?

3
  • 6
    No, there isn't any clean way to do that. You'll need to write those 3 lines of code. Commented Oct 28, 2017 at 17:38
  • You could use reflection -- that's about it. Commented Oct 28, 2017 at 17:39
  • 1
    It might be cleaner to create a copy-constructor inside MyObj and use it whenever you need to create a dup. This approach also avoids potential concurrency issues which you might encounter while "updating" an object field-by-field, since now all you're doing is reference assignment which is an atomic operation. Commented Oct 28, 2017 at 17:40

1 Answer 1

2

You have to identify the object in the list by iterating on it or replacing by a Map<String, MyObj>

Exist some way how to do that without manually setting up all properties?

Sure.
Reflection addresses it but reflection has a cost (it is slower) and it may fail at runtime or give a unexpected behavior.
You can do it manually or better use a library that does the task for you.
But in your case, to handle just 3 fields, it seems an overhead to use reflection.
Just use setters to set them :

MyObj existingObj = ...; // retrieved by a search
existingObj.setName(newObj.getName());
existingObj.setPhone(newObj.getPhone());
existingObj.setAddress(newObj.getAddress());

As alternative, if changing the reference of the object is not a concern, just replace the object actually in the list by which one provided in parameter :

int indexOfTheObject = ...;  // retrieved by a search
objectsList.set(indexOfTheObject, newObj);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.