45

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", "j.doe@supermail.com" ) );

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
user1318796
  • 461
  • 1
  • 4
  • 5

12 Answers12

52

You can do this:

myList.get(3).setEmail("new email");
Random42
  • 8,989
  • 6
  • 55
  • 86
13

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.

Engineero
  • 12,340
  • 5
  • 53
  • 75
Axel Montini
  • 430
  • 6
  • 14
  • 7
    This is not correct. It is true that [ArrayList.get()](https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#get(int)) returns a copy of the element but in the case that the element is an object (like it would be for the question author's List), it returns a copy of the reference to the object. Any modifications you do to this reference will be reflected in the list because the reference points to the exact same place in memory as the object in the list. So this: `myList.get(3).setEmail("j.doe@new.com");` would modify the Customer at pos 3 in the list's email. – Antoine Dahan Apr 13 '16 at 15:53
  • @Antoine Dahan is right. This answer is not correct for objects. Please modify or remove it. – Jacob R Sep 06 '16 at 14:37
9

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("abc@xyz.com");
        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.

Mahendra
  • 323
  • 1
  • 7
6

Assuming Customer has a setter for email - myList.get(3).setEmail("j.doe@supermail.com")

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
4

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", "bert@gmail.com"));
        customers.add(new Customer("Ernie", "ernie@gmail.com"));
        System.out.println("customers before email change - start");
        System.out.println(Customer.toString(customers));
        System.out.println("end");
        customers.get(1).setEmail("new.email@gmail.com");
        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.

Tom
  • 4,096
  • 2
  • 24
  • 38
3

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

hmjd
  • 120,187
  • 20
  • 207
  • 252
3

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("somethingelse@example.com");
SunKing2
  • 311
  • 2
  • 10
2

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.

Kishan Bheemajiyani
  • 3,429
  • 5
  • 34
  • 68
1

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("newEmail@stackoverflow.com")
Svilen
  • 1,377
  • 1
  • 16
  • 23
1

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, ....
          }
Dhiraj
  • 2,687
  • 2
  • 10
  • 34
George
  • 11
  • 1
1

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 = "j.doe@supermail.com".

I hope this help you.

Aliton Oliveira
  • 1,224
  • 1
  • 15
  • 26
0

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("xyz@abc.com");
}
Attaullah
  • 3,856
  • 3
  • 48
  • 63
CuriousCase
  • 659
  • 1
  • 5
  • 12