2017-05-04 1 views
0

그래서 배열 목록에서 요소를 제거 할 것인지 사용자에게 묻고 싶습니다. 배열 목록은 파일에서 읽는 즐겨 찾는 색상 목록입니다. 그래서 배열 목록의 내용이 Red, Orange, Green, Blue라고하자. 사용자 입력을 기반으로 요소를 제거하는 방법을 궁금하네요. 그것과 같은 것이 될 것입니까?내 배열 목록에서 요소를 제거하려면 어떻게합니까?

System.in.println("Which color would you like to remove") 
removeColor = reader.nextString 
if removeColor (//using pseudo code here) contains removeColor, remove from ArrayList 

나는 올바른 길에 있습니까? 지금까지 내 코드를 heres. 감사!

Scanner input = new Scanner(System.in); 
     ArrayList <String> favoriteColors = new ArrayList <String>(); 
     boolean repeat = true; 
     while (repeat) { 

      System.out.println("Enter the name of the file which contains your favorite colors "); 
      String fileName = input.nextLine().trim(); 

      try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { 

       String line; 
       System.out.println("Here are your favorite colors according to the file:"); 
       while ((line = reader.readLine()) != null) {  
        System.out.println(line); 
        favoriteColors.add((line)); 
       }             

       System.out.println("Add more? (y/n)"); 
       if (input.next().startsWith("y")) { 
        System.out.println("Enter : "); 
        favoriteColors.add(input.next()); 
       } else { 
        System.out.println("have a nice day"); 
       } 
       for (int i = 0; i < favoriteColors.size(); i++) { 
        System.out.println(favoriteColors 
       if (input.next().startsWith("y")) { 
       System.out.println("Remove a color?") 
       if (input.next().startsWith("y")) { 
       /something along the lines of the pseudo code I wrote above 
+0

그냥 remove를 호출하면, 같은 것이 List에 있다면 요소를 제거하거나 그렇지 않으면 요소를 제거합니다. – SomeJavaGuy

+0

네, 맞습니다. Arraylist 문서 (https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html), 특히'remove' 메소드를보십시오. – Matt

+0

하나의 힌트 : 다른 사람이 좋아하는 색상 목록을 유지하는 프로그램을 작성하는 경우'favoriteMovies' 변수가 필요하지 않을 것입니다. – ajb

답변

0

HashSet의처럼 나열하지 후 발견 내가 설정 컬렉션을 사용하는 것이 좋습니다 그러나 favoriteColors.remove(index)

사용하여 요소를 제거하기 위해 그 인덱스를 사용하는 경우는, 루프에 일치하는 문자열의 색상을 확인하기 위해 favoriteColors 목록이 모든 키는 고유하며 기존 색상을 확인하기 위해 add (colorString), remove (colorString) 및 contains (colorString)와 같이 여러 가지 유용한 메소드가 포함되어 있습니다.

int index = favoriteColors.indexOf("<the color you want to remove>") 

은 그 다음의 ArrayList에서 해당 요소를 제거

+0

'List # remove'를 호출 할 수 있다면 왜 배열을 반복해야합니까? 그 방법은 단순히 요소를 제거하거나 아무것도하지 않으면 – SomeJavaGuy

+0

List.remove (Object)는 내부적으로 동일한 루프를 수행 한 다음 제거하지만 인덱스를 알고 있으면 인덱스로 제거하는 것이 더 빠릅니다. 목록이 거대하면 더 나은 성능을 위해 세트를 사용하십시오. 다시 색인을 생성하지 마십시오. –

0

당신은 ArrayList를 통해 통과하고 원하는 요소의 인덱스를 얻을 수 있습니다,

favoriteColors.remove(index); 
2

당신은 어떻게 제거 이해할 필요 메서드는 ArrayList에서 작동합니다.

메서드 제거는 다음과 같이 구현됩니다.

당신의 favoriteColors 클래스는 단지 문자열이 그 것이다 다음 경우

:

if (o.equals(elementData[index])) { 

인체 공학적 : 목록에 의해 보류이 기준을 이행 할 수 있어야한다있는 객체를 의미보다

public boolean remove(Object o) { 
    if (o == null) { 
     for (int index = 0; index < size; index++) 
      if (elementData[index] == null) { 
       fastRemove(index); 
       return true; 
      } 
    } else { 
     for (int index = 0; index < size; index++) 
      if (o.equals(elementData[index])) { 
       fastRemove(index); 
       return true; 
      } 
    } 
    return false; 
} 

하지만 맞춤법이 뭔가 있다면, 그 클래스에 equals을 구현해야합니다.

관련 문제