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.

3
  • 2
    why don't you reuse the existing user object? Commented Oct 7, 2015 at 13:32
  • can I do without using the user object? just want to use .contains() if possible Commented Oct 7, 2015 at 13:38
  • 1
    don't knowexactly what you mean, but probably the answer of javatutorial to use a Map is the right solution for you. Commented Oct 7, 2015 at 13:40

5 Answers 5

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;  
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

how about without using loop of an object but i did not know the position of that record from the list?
Is the second block of code. If you now the searchedId (not index).
don't forget to add notifyDataSetChanged() to refresh listview
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).

6 Comments

Thanks, I think this is more efficient than list.
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.
@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 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.
@DavideLorenzoMARINO: there is the LinkedHashMap, which retains insertion order, so that with values() you can have an ordered Collection (see also this). 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.
|
2
 for(User user : userList) {
    if(user.getId == 2) {
        user.setUsername("newUsername")
    }
}

1 Comment

It's just a clear example, how you could implement it - for understanding, not copy/paste, sir...
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")

Comments

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

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.