-1
我對數據結構相當陌生,所以我不是100%確定我正在以正確的方式解決這個問題。我試圖比較兩個嵌套集合,並將匹配的數字存儲在標題爲「交集」的集合中。但是,下面的代碼會拋出ClassCastException
。TreeSets匹配樂透號碼?
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);
}
}
}
當我創建數據結構時,該怎麼看? – user2988501
@user創建實現「Comparator>」的類的對象,並將其傳遞給「TreeSet」構造函數。閱讀比較器的JavaDoc,瞭解如何做到這一點。 –
Eran