2014-02-26 2 views
0

두 세트 A와 B가 있습니다. 조합, 교차점 및 차이점을 찾아야합니다. 지금은 교차 메서드에 초점을 맞추고 retainAll() 메서드를 구현하려고합니다.왜 빈 목록을 반환하는 retainAll()입니까?

나는 모든 코드를 포함하지 않고 달성하고자하는 것과 관련된 메소드 및 데이터 필드 만 포함합니다.

내 문제는 교차로를 찾으려고합니다. 테스트를 실행할 때 웬일인지 빈 목록이 생깁니다. 출력 화면에서 빈 괄호 만 가져옵니다. 왜 이런 일이 일어 났는지 알 수는 없지만 생성자와 관련이 있거나 retainAll 메서드를 설정하는 방법이 있다고 느낍니다. 참고 : 전용 교차 방법에 대한 일이, 노조 방법은 어떤 입력을 완벽하게

감사를 작동, 나는 크게 그것을 시작하는 a의 요소 중 하나가 결코

public class Set<T> { 

//data fields 
private LinkedList<T> L = new LinkedList<T>(); 
private int size; 

//constructor Set with argument used in intersection method 
public Set(Set<T> b) { 

} 


public void add(T item){ 
    L.add(item); 
    size ++; 
} 

// will remove first instance of specified item 
public void remove(T item){ 
    L.remove(item); 
    size--; 
} 


public void retainAll(Set<T> x){ 
    L.retainAll(L); 
} 

public String toString(){ 
    return L.toString(); 
} 

public Iterator<T> iterator(){ 
    return L.iterator(); 
} 



    public static <T> HashSet<T> union(Set<T> a, Set<T>b){ 
    //create new set c, which will be the combination of A and B 
    HashSet<T> c = new HashSet<T>(); 
    Iterator<T> iter1 = a.iterator(); 
    Iterator<T> iter2 = b.iterator(); 

    //go through set A, add to new union 
    while(iter1.hasNext()){ 
     c.add(iter1.next()); 
    } 

    //go through set B, add to new union 
    while(iter2.hasNext()){ 
     c.add(iter2.next()); 
    } 

    return c; 






public static <T> Set<T> intersection(Set<T> a, Set<T>b){ 
    //create new set intersection, which will contain common items of set A and B 
    Set<T> c = new Set<T>(a); 
    c.retainAll(b); 
    return c; 

답변

0
Set<T> c = new Set<T>();  
c.retainAll(b); 
return c; 

c 감사 . 실제로 코드 블록에 a을 언급 한 적이 없습니다. 아마 당신은

Set<T> c = new Set<T>(a);  
+0

죄송합니다. "a"는 원래 매개 변수 였지만 실수로 내 질문에 답을 남기지 않았습니다. 상관 없어요. "a"가 매개 변수 일지라도 여전히 작동하지 않습니다 – overboard182

+0

그러면 생성자의 Set (Set b)가 올바르지 않을 수 있습니다. 해당 코드를 입력하십시오. –

+0

실제로 생성자 안에 코드가 없습니다. 방금 설정 했으므로 Set c = new Set ()은 오류없이 매개 변수로 세트를 허용 할 수 있습니다. 생성자에 코드를 추가하는 것이 좋습니다. 나는 무엇을해야할지 확신하지 못했습니다. – overboard182

0

// 생성자는 당신이 당신의 생성자이기 때문에 다른에 한 세트의 요소를 복사하는 코드를 작성해야 위의 생성자에서 교차 '방식

public Set(Set<T> b) { 

} 

에 사용되는 인수를 설정 의미 아무것도하지 않고. 단순히 설정 인수를 취하는 것입니다. 상기 방법에서

public static <T> Set<T> intersection(Set<T> a, Set<T>b){ 
    //create new set intersection, which will contain common items of set A and B 
    Set<T> c = new Set<T>(a); 
    c.retainAll(b); 
    return c; 

, 이는 "A", "C"는 retainsAll 방법에만 빈 반환하는 요소 복사되지 않을 때.

추신 : 생성자로 뭔가를하십시오.

관련 문제