2011-04-10 32 views
2

需要完成此操作才能使用UseSet类。不知道我所实施的是否100%正确。需要查找基本操作集合/相交/对称差异JAVA

但是我需要联盟和SysDiff的帮助。

public class Set 
{ 
    private ArrayList<Integer> elements; 

    public Set() 
    { 
     elements = null; 
    } 

    public Set(ArrayList<Integer> s) 
    { 
     int i; 
     elements = new ArrayList<Integer>(); 
     for(i=0; i<s.size(); i++) 
      elements.add(s.get(i)); 
    } 

    public Set(int[] s) 
    { 
     int i; 
     elements = new ArrayList<Integer>(); 
     for(i=0; i<s.length; i++) 
      elements.add(s[i]); 
    } 

    public String toString() 
    { 
     //implement this method 
    } 

    public boolean isElement(int elt) 
    { 
     int i 
    for (i=0; i < elements.size(); i++) 
    { 
     if (elements.get(i) == elt) 
     return true; 
    } 
    return false 

    } 

    public int cardinality() 
    { 
     return elements.size(); 
    } 

    public Set intersect(Set s) 
    { 
    Array list <interger> iset = new Array(ist<interger>(); 
    int i; 
    for (i=0; i<elements.size(); i++) 
    { 
     if (s2.isElement (elements.get(i))) 
     iSet.add(elements.get(i))); 
    } 
    return new set(iset) 
} 

    public Set union(Set s) 
    { 
     //implement this method 
    } 

    public Set symDiff(Set s) 
    { 
     //implement this method 
    } 
+0

你在坚持呢? – 2011-04-10 21:28:24

+0

作为一个旁注,'Set'对于你的类的名字是一个相当不幸的选择 - 大多数人会认为你指的是['java.util.Set'](http://download.oracle.com/javase /6/docs/api/java/util/Set.html)... – thkala 2011-04-10 21:32:20

回答

9

你有没有考虑使用Java提供的类之一,如TreeSet?大多数基本设置操作可以使用这样的类作为起点而更容易地实现。

例如:

  • isElement()方法在Set/TreeSet

  • cardinality()命名是size()

  • intersect可以利用来实现retainAll()

  • union()可使用addAll()

  • symDiff()可使用removeAll()以除去从两个集合的并集的交集的元素来实现来实现。

0

Java有其基本的实现。要获得更多功能,请尝试Apache Commons库:

Commons-Collections试图通过提供新的接口,实现和实用程序来构建JDK类。有许多功能,包括...

http://commons.apache.org/collections/

的CollectionUtils类是你的任务(例如,中的addAll:

http://commons.apache.org/collections/api-release/org/apache/commons/collections/CollectionUtils.html#addAll(java.util.Collection,%20java.util.Enumeration)特别有用。

你可以看到实施和这里采取的想法:

http://svn.apache.org/viewvc/commons/proper/collections/trunk/src/java/org/apache/commons/collections/CollectionUtils.java?view=markup