2014-11-16 82 views
-1

我對數據結構相當陌生,所以我不是100%確定我正在以正確的方式解決這個問題。我試圖比較兩個嵌套集合,並將匹配的數字存儲在標題爲「交集」的集合中。但是,下面的代碼會拋出ClassCastExceptionTreeSets匹配樂透號碼?

public class Details { 
    public static void main(String[] args) { 
     Set<Integer> myNums = new TreeSet<Integer>(); 
     myNums.add(1); 
     myNums.add(2); 
     myNums.add(3); 
     myNums.add(4); 
     myNums.add(5); 
     myNums.add(6); 

     Set<Integer> myNums2 = new TreeSet<Integer>(); 
     myNums2.add(7); 
     myNums2.add(8); 
     myNums2.add(3); 
     myNums2.add(10); 
     myNums2.add(11); 
     myNums2.add(12); 

     Set<Set<Integer>> myTicket = new TreeSet<Set<Integer>>(); 
     myTicket.add(myNums); 
     myTicket.add(myNums2); 

     Set<Integer> lottoNums = new TreeSet<Integer>(); 
     lottoNums.add(1); 
     lottoNums.add(2); 
     lottoNums.add(3); 
     lottoNums.add(4); 
     lottoNums.add(5); 
     lottoNums.add(6); 

     Set<Set<Integer>> lottoNums1 = new TreeSet<Set<Integer>>(); 
     lottoNums1.add(lottoNums); 

     // keep only the winning numbers from the user's ticket 
     Set<Set<Integer>> intersection = new TreeSet<Set<Integer>>(myTicket); 
     intersection.retainAll(lottoNums1); 

     // print results 
     System.out.println("Your ticket numbers are " + myTicket); 
     System.out.println("The winning numbers are " + lottoNums1); 
     System.out.println(); 
     System.out.println("You had " + intersection.size() 
       + " matching numbers."); 
     if (intersection.size() > 0) { 
      double prize = 100 * Math.pow(2, intersection.size()); 
      System.out.println("The matched numbers are " + intersection); 
      System.out.println("Your prize is $" + prize); 
     } 
    } 
} 

回答

2

你應該閱讀TreeSet()構造函數的文檔使用的是:

/** 
* Constructs a new, empty tree set, sorted according to the 
* natural ordering of its elements. All elements inserted into 
* the set must implement the {@link Comparable} interface. 
* Furthermore, all such elements must be <i>mutually 
* comparable</i>: {@code e1.compareTo(e2)} must not throw a 
* {@code ClassCastException} for any elements {@code e1} and 
* {@code e2} in the set. If the user attempts to add an element 
* to the set that violates this constraint (for example, the user 
* attempts to add a string element to a set whose elements are 
* integers), the {@code add} call will throw a 
* {@code ClassCastException}. 
*/ 
public TreeSet() { 
    this(new TreeMap<E,Object>()); 
} 

要添加Set<Integer>Set<Set<Integer>>,但Set<Integer>沒有實現可比。

解決方法是使用接收Comparator作爲參數的構造函數。

TreeSet(Comparator<? super E> comparator) 

Comparator(你的情況Comparator<Set<Integer>>)將持有的如何將兩個Set<Integer>實例比較的邏輯。

+0

當我創建數據結構時,該怎麼看? – user2988501

+0

@user創建實現「Comparator >」的類的對象,並將其傳遞給「TreeSet」構造函數。閱讀比較器的JavaDoc,瞭解如何做到這一點。 – Eran