2016-10-01 3 views
1

두 개의 다른 ArrayList 인스턴스 (Container 유형과 String 유형 중 하나)이 있습니다. 첫 번째는 한 국가의 "금지 된 제품"(문자열) 목록이며, 다른 하나는 선박의 컨테이너 목록입니다. 배는 국가를 통해 여행하며 컨테이너는 금지 된 상품을 검색합니다. 컨테이너 contains 금지 된 상품 인 경우 해당 컨테이너를 제거/삭제해야합니다. 내가 inspect에 컨테이너 선박을 방법을 만들려고하고ArrayList에서 다른 ArrayList의 값을 검색하십시오.

public void removeContainer(int i) 
{ 
    if(i >= 0 && i < containers.size()) { 
     Container r = containers.remove(i); 
     totalWeight = totalWeight - r.getWeight(); 
    }  
} 

:

public Customs(String country) 
{ 
    countryName = country; 
    bannedGoods = new ArrayList<String>(); 
} 

public Ship(String n, double weight) 
{ 
    emptyWeight = totalWeight = weight; 
    name = n; 
    containers = new ArrayList<Container>(); 
}  

은 이미 컨테이너를 제거하는 선박 클래스의 메소드가 있습니다. 각각의 배열에 대해 두 개의 for-loops를 사용하고 싶지만 올바르게 만들 수없는 것 같습니다! 누군가가 두 개의 루프를 사용하여 어레이를 검색하도록 도울 수 있습니까? 또한 루프에서 반복자 (구체적으로 remove 함수)를 사용해야한다고 생각하지만, 이는 나에게 혼란 스럽다. 이터레이터 remove 메소드를 이미 클래스 배에서 작성한 메소드로 대체해야합니까?

for(String good : bannedGoods) { 
    Iterator<String> it = ship.containers.iterator(); 
     while (it.hasNext()) 
      if (ship.contains(good)) 
       it.remove(); 
} 

답변

0

난 당신이 루프이 필요하다고 생각하지 않습니다 반복자에서 내 시도는 여기

public void inspect(Ship ship) 
{ 
    for (String good : bannedGoods) { 
     for (String con : containers) { 
      if (con.contains(good) { 
       container.remove(); 
      } 
     } 
    } 

을 그리고 다음은 내가 가진 것입니다. 금지 된 제품을 반복해야합니다. & 단순히 컨테이너에서 제거하십시오. 이는 주먹 라인에 언급 된 바와 같이 containers 목록 유형 string의 가정하면 또한

: I have two different arrayLists of the same type String

public void inspect(Ship ship, ArrayList<String> bannedGoods){ 
    if (ship == null || bannedGoods == null || bannedGoods.isEmpty()) 
     return; 
    for(String good : bannedGoods){ 
     ship.containers.remove(good); 
    } 
} 

하면, Containers 유형 Container이며 그것을 통해 접근 용기 (Arraylist of string)의 목록이 포함되어 있습니다 방법 get_containers()는, 다음 작동합니다 :

public void inspect(Ship ship, ArrayList<String> bannedGoods){ 
    if (ship == null || bannedGoods == null || bannedGoods.isEmpty()) 
     return; 
    for(String good : bannedGoods){ 
     for(Container container : ship.containers){ 
      container.get_containers().remove(good); 
     } 
    } 
} 
+0

'containers'는'Container' 객체가 아닌 문자열의 목록입니다 : 당신의 Customs 클래스 내에서

, 당신은 Container 인스턴스의 기분을 상하게 제거 Iterator의에게 remove 방법을 사용하십시오. 또한'inspect'는 아마도'Customs'의 인스턴스 메소드이기 때문에'bannedGoods'리스트에 직접 접근 할 수 있습니다. – nbrooks

+0

OP가 이것을 첫 번째 라인으로 작성했습니다. '동일한 유형의 String을 가진 두 개의 다른 arrayList를가집니다.' –

+0

두 번째리스트가 'Container'내에있는 것으로 보입니다. 선박 생성자'containers = new ArrayList ();'을 참조하십시오. – nbrooks

0

당신은 당신이 지금 사용하고있는 방법에 충실 할 수 있습니다. 그러나 iterator의 remove 메소드를 사용하거나 iterator를 사용하지 않아도된다는 것을 명심하십시오. 디자인하는 동안 실제로 아주 가까이있어

for (int i = 0; i < bannedGoods.size(); i++) 
{ 
    for (int j = 0; j < containers.size();) // NOTE: no j++ here 
    { 
     Container c = containers.get(j); 
     if (c.contains(bannedGoods.get(i)) 
      c.removeContainer(j); 
     else 
      j++; // only if you don't remove the container increment 
       // j - when removing the next element gets current 
       // index 
    } 
} 
0

, 당신은 객체 지향 프로그래밍의 원칙에 초점을 맞추고의 좋은 일을 한 : 그래서 당신의 제거 방법을 사용하거나 Iterable을 구현하거나 대신 반복자의 인덱스를 사용하는 너의 수업. 나는 당신이 지금 집중해야 할 것들이 당신의 타입에 더주의를 기울이고 있다고 생각합니다. 다음은 Container가 표시되지 않습니다 수업에 몇 가지 제안 수정 (하지만 나는 그것이 용기가 내부에 어떤 좋은 s 여부를 확인하는 public boolean contains (String s) 방법을 가지고 있으리라 믿고있어.

import java.util.*; 

public class Ship implements Iterable<Container> { 
    private double emptyWeight, totalWeight, weight; 
    private String name; 
    private List<Container> containers = new ArrayList<Container>(); 

    public Ship(String n, double weight) { 
     emptyWeight = totalWeight = weight; 
     name = n; 
    } 

    private void removeContainer(int i) { 
     if (i >= 0 && i < containers.size()) { 
      Container r = containers.remove(i); 
      totalWeight = totalWeight - r.getWeight(); 
     }  
    } 

    public Iterator<Container> iterator() { 
     return new Iterator<Container> { 
      private index = 0; 
      private Container previous = null; 

      public boolean hasNext() { 
       return index < containers.size(); 
      } 

      public Container next() { 
       if (!hasNext()) { 
        throw new NoSuchElementException(); 
       } 
       previous = containers.get(index++); 

       return previous; 
      } 

      public void remove() { 
       if (previous == null) { 
        throw new IllegalStateException(); 
       } 

       removeContainer(containers.indexOf(previous)); 

       previous = null; 
      } 
     }; 
    } 
} 

나는 내 removeContainer을 유지하는 것이 좋습니다 당신의 Ship 클래스는 컨테이너가 제거되었을 때 그 가중치가 어떻게 변하는 지 추적 할 책임이 있기 때문에 외부 클래스가 containers 목록에 직접 액세스하는 것을 허용하지 마십시오. 다른 방법으로 값을 추가하거나 제거하지 못하게 할 수 있습니다 그 목록은 weight을 올바르게 업데이트하지 않고 containers 목록을 비공개로 설정하고 Iterator을 공개하는 것이 좋습니다. 클래스의 사용자가 컨테이너와 상호 작용할 수 있도록합니다.

import java.util.*; 

public class Customs { 
    private String countryName; 
    private List<String> bannedGoods = new ArrayList<String>(); 

    public Customs(String country) { 
     countryName = country; 
    } 

    public void inspect(Ship ship) { 
     for (String good : bannedGoods) { 
      for (Iterator<Container> it = ship.iterator(); it.hasNext();) { 
       Container container = it.next(); 

       if (container.contains(good) { 
        it.remove(); 
       } 
      } 
     } 
    } 
} 
관련 문제