2011-11-24 2 views
0

고객 개체에서 값을 선택하여 가져 오려고합니다. 내가하고 싶은 일은 "702312"와 같은 개인 번호를 입력하고 "702312"와 같은 데이터 회원 개인 번호를 가진 고객 객체를 검색하는 것입니다. 그리고 그것을 발견했을 때 나머지 가치를 얻거나 내용을 변경하고 싶습니다. 이 클래스는 Customer 클래스의 고객 객체를 생성 한 다음 arraylist에 저장하는 코드입니다.Java의 arraylist에있는 객체 메소드에서 값을 가져 오겠습니까?

// create a new customer object and send personal number, name and account number to constructor 
Customer customer = new Customer(personalNumber, name, newAccountNumber); 

// create an arraylist to store customer objects 
ArrayList<Customer> customerList = new ArrayList<Customer>(); 

// add the new customer object to arraylist that holds all customer objects 
customerList.add(customer); 

이 값에 도달하려고 시도했지만 작동하지 않아 일부 도움이 필요합니까? 나는이 시도

if(customer.getAccountOwnerPersonalNumber() == "702312")... 

:

// search for customer 
for (Customer customer : customerList) { 
if(customer.getAccountOwnerPersonalNumber() == "702312"){ 
    System.out.println("OK!!!"); 
    } 
} 

그리고 대신

또한 이런 식으로 테스트 한 마지막
if(customer.personalNumber == "702312")... 

:

for(int i=0;i<customerList.size();i++){ 
    if(customerList.get(i).getAccountOwnerName() == "702312"); 
    System.out.println("OK"); 
    break; 
} 

아니에요 내가 제대로하고 있는지 확실히!? 도움은 preciated입니다! 감사!

+0

어떤 유형이 .getAccountOwnerName() 함수를 반환합니까? 나는 숫자와 문자열을 비교하려고 노력한다고 생각한다. – Gatekeeper

+0

당신은'System.out.println' 메소드를 올바르게 호출하지 않는다. 'System.out.println ("OK");' – Michael

+0

@ 마이클 : 농담하는거야? – BalusC

답변

5

당신은 (그렇지 않으면 그들은 단지참조를 기준으로 비교됩니다) 내부 값 객체String 같은의를 비교하기 위해 equals() 방법을 사용해야합니다

if (customer.getAccountOwnerPersonalNumber().equals("702312")) { 
    System.out.println("OK!!!"); 
} 

또는 더 나은, 경우 수 해당되는 경우, 단지 그것을 PRI을,

if ("702312".equals(customer.getAccountOwnerPersonalNumber())) { 
    System.out.println("OK!!!"); 
} 

또는 : 잠재적 null을 반환 == 당신이 의도 한 방식으로 작동 할 수 있도록, int 같은을 mitive :

if (customer.getAccountOwnerPersonalNumber() == 702312) { 
    System.out.println("OK!!!"); 
} 
+0

감사합니다. equals를 사용하면 정상적으로 작동합니다! 그러나 개인 번호가 "702312"인 개체에서 나머지 개체 데이터 멤버를 얻으려면 어떻게해야합니까? –

+0

루프 안의 다른'List'에서 그것들을 수집하십시오. 붙어 있다면 새로운 질문을하십시오. – BalusC

+0

나는 당신의 대답을 이해하고 있는지 모르겠다. 약간의 코드를 보여줄 시간이 있습니까? –

1

private int accountOwnerPersonalNumber; 

하기는 .equals()를 원하는 :

if(customerList.get(i).getAccountOwnerName().equals("702312")) 
1

customer.getAccountOwnerPersonalNumber() == "702312" 이것은 당신이 캔트 잘못 그들의 객체 유형을 비교하기 때문에 그것들을 비교하십시오. 당신은 쿼리 데이터가 문자열로 당신은 그래서 전체 일들이 밝혀 질 것 등호()

를 사용해야 할 경우에 다음의 경우이

if(customer.getAccountOwnerPersonalNumber().equals("702312")) 

or this is better 

if("702312".equals(customer.getAccountOwnerPersonalNumber())) 
0

처럼해야

if (customer.getAccountOwnerPersonalNumber(). equals ("702312")) { System.out.println ("OK !!!"); }

0

고객을 비교하려고합니다.personalNumber to "702312" 문자열입니다. 따라서 고객 번호는도 문자열입니다. 맞다면 == 연산자 대신 String.equals() 메서드를 사용해보십시오. 이것은이 연산자가 원하는 값 대신 객체를 비교하기 때문입니다.

if(customer.getAccountOwnerPersonalNumber().equals("70312");) 
    ... 
0

난 당신이 java.util.CollectionsbinarySearch(...) 방법을 사용하는 것이 좋습니다 것입니다. 주문 O (log n) (이 경우, ArrayListRandomAccess을 구현하기 때문에)는 for 루프를 수행 할 때 얻은 O (n) 순서보다 뛰어납니다. 원하는 검색 기준에 따라 목록을 정렬하는 것을 잊지 마세요,

private static class CustomerPersonalNumberComparator implements Comparator<Customer> { 

     @Override 
     public int compare(Customer o1, Customer o2) { 
      return o1.getPersonaNumber().compareTo(o2.getPersonaNumber()); 
     } 

    } 

또한 :

있습니다 (이 경우 "personalNumber"에서) 원하는 고객 필드 (들)에 대한 별도의 비교를 할 수 있습니다 그것에 이진 검색을 사용하기 전에 (비교기) :

Collections.sort(customerList,new CustomerPersonalNumberComparator()); 
int desiredIndex = Collections.binarySearch(customerList, new Customer("658",null,null), new CustomerPersonalNumberComparator()); 
Customer desiredCustomer = desiredIndex == -1 ? null : customerList.get(desiredIndex); 

그리고 이진 검색은 원하는 요소에 대한 우리의 배열 내부의 위치을 반환하거나 아무 것도 -1 발견되지 않았던 경우는 것을 잊지 마세요. 따라서 반환 된 위치를 사용하여 목록에서 원하는 인스턴스를 검색해야합니다.

관련 문제