2012-04-07 4 views
28

나는 Customer 개의 오브젝트를 ArrayList에 저장했습니다. 내 Customer 클래스에는 NameEmail의 두 데이터 멤버가 있습니다. 이제 고객 "Doe"에 대해서만 Email을 수정하고 싶습니다. "미상"이 목록에 인덱스 3에있는 경우 ArrayList - 객체의 멤버를 수정하는 방법?

지금, 나는이 줄을 쓸 수 있습니다 알고

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

을하지만 그 새로운 객체를 생성하는 것을 의미한다. 제가 아주 큰 목록을 가지고 있다면, 그 과정은 매우 느릴 것이라고 생각합니다. ArrayList에 저장된 Object의 데이터 멤버에 직접 액세스 할 수있는 다른 방법이 있습니까? ArrayList가 아닌 다른 종류의 Collection을 사용하고 있습니까? myList.get(3).setEmail("[email protected]")

답변

3

은 이메일 세터가 있습니다.

2

사용 myList.get(3) 현재 객체에 접근하고이를 수정, 변경 될 수있는 방법 Customer의 인스턴스를 가정 할 - Customer 가정

36

이 작업을 수행 할 수 있습니다

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

것은 당신은 다음 당신이 단지에 '도착'한 고객의 속성을 수정 컬렉션 얻을 다만 할 수 있습니다. 컬렉션을 수정할 필요가 없습니다도 신규 고객 생성 할 필요가있다 :

당신이 필요로하는 경우
int currentCustomer = 3; 

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

빠른 조회 (기본적으로 일정 시간) 컬렉션에 저장된 객체의 대신 목록의지도를 사용해야은 .

개체를 빠르게 반복해야하는 경우 목록을 사용해야합니다. 귀하의 경우 그래서

...

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]") 
3

내가 어떻게하는지 보여 당신이 개 클래스를 썼다; 주 고객. 당신은 메인 클래스를 실행하는 경우에 당신은 무슨 일이 일어나고 있는지 참조 :

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"); 
    } 

} 

가이 실행을 얻을 수 2 개 클래스, 홈페이지 및 고객을 올바른 클래스 두 클래스에서 내용을 붙여 복사; 그런 다음 Main 클래스를 실행하십시오.

1

arraylist를 통해 반복하여 인덱스를 식별하고 수정해야 할 개체를 식별 할 수 있습니다. 아래 같은 위해를 위해 - 각 사용할 수 있습니다 :이 고객 기준의 모든 속성을 변경하는 경우, 고객의 ArrayList에 존재하는 물체에 대한 참조입니다 여기에

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

, 이러한 변경에 저장된 객체에 반영됩니다 Arraylist.

+0

가득 listArrays와 잘 작동합니다. -> "Doe".equals (customer.getName()), 현재 : 첫 번째 경기가 끝난 후 왜 멈추지 않습니까? –

+0

정정 해 주셔서 감사합니다. 두 가지 사항을 명심하시기 바랍니다. – Mahendra

0

음, Pojo Entity를 사용하여 이것을 수행 할 수 있습니다. 유물을 가져와 데이터를 설정해야합니다.

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

그런 식으로 할 수 있습니다. 또는 다른 매개 변수를 설정할 수도 있습니다.

0

시도해보십시오. 이것은 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]"); 
} 
6

수정 됨. 나는 틀렸다. 이것은 요소 재 할당에만 적용된다. 반환 된 객체가 새 객체를 참조하지 않는다고 생각했습니다.

할 수 있습니다.

: 이유가 무엇입니까?
: get() 메서드는 원본을 참조하는 객체를 반환합니다.

그래서, 실제로 의해을 참조 객체의 메소드를 이용하여/값을 할당하는 myArrayList.get(15).itsVariable = 7
또는
myArrayList.get(15).myMethod("My Value"),
쓰면 돌려 온 (이것은 변화가 원래의 객체에 적용된다 수단)

당신이 을 할 수있는 유일한 방법은 myArrayList.get(15) = myNewElement입니다. 이렇게하려면 list.set() 메서드를 사용해야합니다. 여기가 기능하지 않고

+4

올바르지 않습니다. [ArrayList.get()] (https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#get (int))는 요소의 복사본을 반환하지만 요소가 객체 인 경우 (질문 작성자의 List 처럼) 객체에 대한 참조 사본을 반환합니다. 이 참조에 대한 수정 사항은 목록에있는 객체와 똑같은 장소를 참조하기 때문에 목록에 반영됩니다. 그래서 이것은 : myList.get (3) .setEmail ("[email protected]");'목록의 이메일에서 pos 3의 고객을 수정합니다. –

+0

@Antoine Dahan이 옳습니다. 이 대답은 객체에 맞지 않습니다. 수정하거나 제거하십시오. –

0

... 그것은 객체

예를 들어이 저장 NPE하지 `

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, .... 
      } 
관련 문제