5

How can I update the record from my Arraylist object?

e.g:

List<User> userList = new ArrayList<User>();

User user = new User();
user.setUserId(1);
user.setUsername("user1");
userList.add(user);

User user = new User();
user.setUserId(2);
user.setUsername("user2");
userList.add(user);

User user = new User();
user.setUserId(3);
user.setUsername("user3");
userList.add(user);

Now I want to update the specific records on my ArrayList. Let's say I want to update the username of user id #2. e.g:

User user = new User();
user.setUserId(2);
user.setUsername("new_username2");

//before i want to remove or update the record on the list which contain user id #2
userList.add(user);

Something like I want to search from the list that userList.contains(2) then remove or update it with the new values.

enzo
  • 9,861
  • 3
  • 15
  • 38
Cris
  • 437
  • 2
  • 5
  • 15

5 Answers5

8

If you know the position of the element do only the following:

userList.get(index).setUsername("newvalue");

If not, you need to loop all the elements to find the element to update

for (User user : userList) {
    if (user.getUserId().equals(searchedId)) {
        user.setUsername("newvalue");
        break;  
    }
}
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
5

In your case I think it's better using a Map instead of a List:

Map<Integer, User> userMap = new HashMap<Integer, User>();

User user = new User();
user.setUserId(1);
user.setUsername("user1");
userMap.put(user.getUserId(), user);

user = new User();
user.setUserId(2);
user.setUsername("user2");
userMap.put(user.getUserId(), user);

user = new User();
user.setUserId(3);
user.setUsername("user3");
userMap.put(user.getUserId(), user);

In this way, you can search directly for the userId you need:

User userToModify = userMap.remove(idToModify);
userToModify.setUsername("new name");
userToModify.setUserId(54);
userMap.put(user.getUserId(), userToModify);

If you need to find object only by one field (userId, in this case), a Map is far more efficient and easy to use (and to maintain).

javatutorial
  • 1,916
  • 15
  • 20
  • Thanks, I think this is more efficient than list. – Cris Oct 07 '15 at 13:47
  • Yes it is more efficient if your list is used only in this context. If you need also a list (for other part of code) you need to check if it is better to have two different data structures or only one. – Davide Lorenzo MARINO Oct 07 '15 at 14:23
  • @DavideLorenzoMARINO: unless you need specific List features, you don't have to use another different data structure, as Map gives you a nice `values()` method, that returns a `Collection` of all the values stored in the Map (the User objects, in this case). Usually that's enough. Moreover, since the returned `Collection` is backed by the Map (i.e., its objects are tightly linked to it), every operation on the `Collection` has effects on the Map too (elements removal, object updating, etc.), thus avoiding code and data-structure duplication. :) – javatutorial Oct 07 '15 at 14:36
  • @javatutorial you are right. But a list is an ordered collection. A map is not. If the code needs to know informations about the insertion order is needed to mantain a list. I don't know the code, so why I said "if you need also a list (for other part of code)". values() is not equivalent because the insertion order is not respected. – Davide Lorenzo MARINO Oct 07 '15 at 16:02
  • @DavideLorenzoMARINO: there is the `LinkedHashMap`, which retains insertion order, so that with `values()` you can have an ordered Collection (see also [this](http://stackoverflow.com/questions/2923856/is-the-order-guaranteed-for-the-return-of-keys-and-values-from-a-linkedhashmap-o)). It's usually a bad idea duplicating the data structure, as you always need to do every operation twice (one on the Map and one on the List, for example). But of course if you need some specific features (like the Queue-Deque methods of `LinkedList`) that can be a solution. – javatutorial Oct 08 '15 at 07:59
  • @javatutorial nice idea! – Davide Lorenzo MARINO Oct 08 '15 at 08:00
2
 for(User user : userList) {
    if(user.getId == 2) {
        user.setUsername("newUsername")
    }
}
i23
  • 508
  • 2
  • 12
  • It's just a clear example, how you could implement it - for understanding, not copy/paste, sir... – i23 Oct 07 '15 at 13:41
2

If you need to just update the name then you do not need to create a new object and insert it into the list. As @Davide has pointed out you can iterate over the list and set the username.

I would suggest on top of that, in the interest of efficiency, to use a Hashtable<Integer, User> userTable rather than a list to prevent the iteration over the whole list to find the right User

This way you can get the user by its ID efficiently get set the username as shown here userTable.get(id).setUsername("new username")

triadiktyo
  • 479
  • 2
  • 9
0

If you want to change some attributes on the object at position K in the list, as mentioned above, use:

userList.get(k).setAttribute(someValue);

However, if you want to replace the entire object with a new one, use the set() method of List:

userList.set(k, U); //where U is a new User

Another option is to delete the item and add a new item in its place:

userList.remove(k);
userList.add(k, U);

However, if item k was the last element of the list before its removal, then you need to do:

userList.remove(k); userList.add(U); //added at the end of the list