为什么retainAll()返回一个空列表?

时间:2014-02-26 23:53:55

标签: java set

我有两套A和B.我必须找到联合,交集和差异。现在我专注于交集方法,我正在尝试实现retainAll()方法。

我不会包含我的所有代码,只包括与我想要完成的内容相关的方法和数据字段。

我的问题在于试图找到交集。出于某种原因,当我进行测试时,我得到一个空列表。我只在输出屏幕上显示空括号。我无法弄清楚为什么会发生这种情况,但我觉得它与构造函数或我如何设置retainAll方法有关。注意:这只发生在交集方法中,union方法完美地运行

感谢您的任何意见,我非常感谢

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;

2 个答案:

答案 0 :(得分:0)

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

c永远不会有a的任何元素。事实上,您从未在该代码块中的任何位置提到a。也许你的意思是

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

答案 1 :(得分:0)

// constructor使用交集方法

中使用的参数进行设置
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方法将仅返回空。

PS:请对构造函数执行某些操作。

相关问题