[java] ArrayList - How to modify a member of an object?

I have a number of Customer objects stored in an ArrayList. My Customer class has 2 data members: Name and Email. Now I want to modify just the Email for Customer "Doe".

Now if "Doe" is located at index 3 in the list, I know I can write this line:

myList.set( 3, new Customer( "Doe", "[email protected]" ) );

But that means creating a new object. If I have a very big list, I suppose the process would be very slow. Is there any other way to directly access the data member of an Object stored in an ArrayList, maybe by using another kind of Collection than ArrayList?

This question is related to java collections pojo

The answer is


Fixed. I was wrong: this only applies on element reassignment. I thought that the returned object wasn't referencing the new one.

It can be done.

Q: Why?
A: The get() method returns an object referencing the original one.

So, if you write myArrayList.get(15).itsVariable = 7
or
myArrayList.get(15).myMethod("My Value"),
you are actually assigning a value / using a method from the object referenced by the returned one (this means, the change is applied to the original object)

The only thing you can't do is myArrayList.get(15) = myNewElement. To do this you have to use list.set() method.


If you need fast lookup (basically constant time) of a object stored in your collection you should use Map instead of List.

If you need fast iteration of the objects you should use List.

So in your case...

Map<String,Customer> customers = new HashMap<String,Customer>();

//somewhere in the code you fill up the Map, assuming customer names are unique
customers.put(customer.getName(), customer)

// at some later point you retrieve it like this; 
// this is fast, given a good hash
// been calculated for the "keys" in your map, in this case the keys are unique 
// String objects so the default hash algorithm should be fine
Customer theCustomerYouLookFor = customers.get("Doe");

// modify it
theCustomerYouLookFor.setEmail("[email protected]")

I wrote you 2 classes to show you how it's done; Main and Customer. If you run the Main class you see what's going on:

import java.util.*;

public class Customer {

    private String name;
    private String email;

    public Customer(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return name + " | " + email;
    }

    public static String toString(Collection<Customer> customers) {
        String s = "";
        for(Customer customer : customers) {
            s += customer + "\n";
        }
        return s;
    }

}


import java.util.*;

public class Main {

    public static void main(String[] args) {
        List<Customer> customers = new ArrayList<>();
        customers.add(new Customer("Bert", "[email protected]"));
        customers.add(new Customer("Ernie", "[email protected]"));
        System.out.println("customers before email change - start");
        System.out.println(Customer.toString(customers));
        System.out.println("end");
        customers.get(1).setEmail("[email protected]");
        System.out.println("customers after email change - start");
        System.out.println(Customer.toString(customers));
        System.out.println("end");
    }

}

to get this running, make 2 classes, Main and Customer and copy paste the contents from both classes to the correct class; then run the Main class.


Well u have used Pojo Entity so u can do this. u need to get object of that and have to set data.

myList.get(3).setEmail("email");

that way u can do that. or u can set other param too.


You can iterate through arraylist to identify the index and eventually the object which you need to modify. You can use for-each for the same as below:

for(Customer customer : myList) {
    if(customer!=null && "Doe".equals(customer.getName())) {
        customer.setEmail("[email protected]");
        break;
    }
}

Here customer is a reference to the object present in Arraylist, If you change any property of this customer reference, these changes will reflect in your object stored in Arraylist.


Any method you use, there will always be a loop like in removeAll() and set().

So, I solved my problem like this:

for (int i = 0; i < myList.size(); i++) {

        if (myList.get(i).getName().equals(varName)) {

            myList.get(i).setEmail(varEmail);
            break;

        }
    }

Where varName = "Doe" and varEmail = "[email protected]".

I hope this help you.


Without function here it is...it works fine with listArrays filled with Objects

example `

al.add(new Student(101,"Jack",23,'C'));//adding Student class object  
      al.add(new Student(102,"Evan",21,'A'));  
      al.add(new Student(103,"Berton",25,'B'));  
      al.add(0, new Student(104,"Brian",20,'D'));
      al.add(0, new Student(105,"Lance",24,'D'));
      for(int i = 101; i< 101+al.size(); i++) {  
              al.get(i-101).rollno = i;//rollno is 101, 102 , 103, ....
          }

Assuming Customer has a setter for email - myList.get(3).setEmail("[email protected]")


You can do this:

myList.get(3).setEmail("new email");

Try this.This works while traversing the code and modifying the fields at once of all the elements of Arraylist.

public Employee(String name,String email){
this.name=name;
this.email=email;
}

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setEmail(String email) {
this.email = email;
}

public String getEmail() {
return email;
}

for(int i=0;i++){
List.get(i).setName("Anonymous");
List.get(i).setEmail("[email protected]");
}

You can just do a get on the collection then just modify the attributes of the customer you just did a 'get' on. There is no need to modify the collection nor is there a need to create a new customer:

int currentCustomer = 3;

// get the customer at 3
Customer c = list.get(currentCustomer);
// change his email
c.setEmail("[email protected]");

Use myList.get(3) to get access to the current object and modify it, assuming instances of Customer have a way to be modified.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?

Examples related to pojo

Spring Data JPA map the native query result to Non-Entity POJO Convert a Map<String, String> to a POJO What is java pojo class, java bean, normal class? Date format Mapping to JSON Jackson What is the difference between field, variable, attribute, and property in Java POJOs? ArrayList - How to modify a member of an object? How to convert POJO to JSON and vice versa? How to create a POJO? Difference between DTO, VO, POJO, JavaBeans? What is the difference between a JavaBean and a POJO?