2011-12-03 2 views
0

나는 토끼의 Arraylist가 있습니다. 각 토끼의 이름은 String이고 String[]입니다.ArrayList Java에서 항목을 제거합니다. 접근자를 필요로합니다.

rabbit(String name, String[] informations) 

가 나는 ArrayList에서 이러한 토끼가, 이제 rabbitlist를 호출 할 수 있습니다. 나는 밖으로 이름을 얻기 위해 각 루프에 대해 추측하거나 루프 동안의 일종을해야

public void removerabbit(String name) 

:

나는 방법처럼 만들고 싶어. 토끼의 이름을 알려주는 접근 자 getName()을 만들었습니다. 어떻게 내 뇌를 감싸고 있는지 알아내는 데 문제가 있습니다. 단순해야합니다. 당신은 java.util.Iterator를 목록에 반복하는 동안 항목을 제거 할 수 있어야

+0

모두를 돕기 위해'Rabbit' 코드를 포함 시키길 권합니다. – Kowser

답변

1

당신의 Rabbit의 이름이 Rabbit에 대한 고유 식별자, 당신은 Rabbitequals 방법을 대체 할 수 있습니다 이름 만 확인하면됩니다. 이 경우 ArrayList의 빌드 인 제거 메소드가 제거 할 요소를 판별하기 위해 equals 메소드를 사용하므로 removeRabbit 메소드는 매우 직관적입니다.

public void removeRabbit(String rabbitName){ 
    //just create a new Rabbit with rabbitName as name, 
    //and remove it from the list 
    rabbitList.remove(new Rabbit(rabbitName)); 
} 

경우에 따라 목록을 반복 할 수 있습니다. 다음 코드는 지정된 이름을 가진 모든 토끼를 제거합니다. 첫 번째 토끼 만 제거하려는 경우 첫 번째 토끼를 제거한 후에 루프를 중지해야합니다.

public void removeRabbit(String name){ 
    Iterator<Rabbit> rabbitIterator = rabbitList.iterator(); 
    while (rabbitIterator.hasNext()) { 
    Rabbit next = rabbitIterator.next(); 
    if (name.equals(next.getName())){ 
     rabbitIterator.remove(); 
    } 
    } 
} 
+0

Iterator를 설명 할 수 있습니까 ?? while 루프와 if 문장을 알고 있습니다. – Swupper

+0

http://en.wikipedia.org/wiki/Iterator Iterator의 개념을 잘 설명합니다. – Robin

+0

@Swupper - Oracle Java Tutorial ... 또는 Java Java 교과서를 읽는 데 시간이 걸리는 것처럼 들립니다. –

0

Iterator<Rabbit> it = rabbits.iterator(); 
String nameForRemove = "rabbitName"; 
while(it.hasNext()) { 
    if(it.next().getName().equals(nameForRemove)) it.remove(); 
} 
0

당신은 rabbitList에 주어진 name.Get 인덱스와 토끼를 찾을 수 rabbitList를 통해 반복해야하고, 당신의 코드가 같은 것을해야한다 rabbitList 에서 제거됩니다,

public boolean removeRabbit(String name){ 
Rabbit rabbit; 
Iterator it = rabbitList.iterator(); 
while (it.hasNext()) { 
    rabbit=it.next(); 
    if(name.equals(rabbit.getName()){  
     int index =rabbitList.indexOf(rabbit); 
     //remove rabbit at this index,returns boolean 
     return rabbitList.remove(index); 
     } 
    } 
return false; 
} 

이 작동합니다 ... 일부 변경 될 수있다

편집 :

public boolean removeRabbit(String name){ 
Rabbit rabbit; 
int index; 
Iterator it = rabbitList.iterator(); 
while (it.hasNext()) { 
    rabbit=it.next(); 
    if(name.equals(rabbit.getName()){  
     index =rabbitList.indexOf(rabbit); 
     } 
    } 
//remove rabbit at this index,returns boolean 
return rabbitList.remove(index); 
} 

이것은 약간의 변화가있을 수 있습니다 ...

+0

반복하는 동안 요소를 목록에서 제거하면 안됩니다. iterator에서 제거하십시오. – Robin

+0

@Robin : 반복 할 때 왜 제거 할 수 없습니까? –

+0

http://docs.oracle.com/javase/6/docs/api/java/util/Iterator.html#remove()를 참조하십시오. – Robin

관련 문제