I'm pretty new to data structures, so I am not 100% sure I am going about this problem the right way. I am trying to compare two nested sets against each other, and store the matching numbers in the set titled 'Intersection'. However, the code below throws a ClassCastException
.
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);
}
}
}
You should read the docs of the
TreeSet()
constructor you are using :You are adding a
Set<Integer>
to yourSet<Set<Integer>>
, butSet<Integer>
doesn't implement Comparable.The solution is to use the constructor that receives a
Comparator
as a parameter.The
Comparator
(in your caseComparator<Set<Integer>>
) would hold the logic of how to compare twoSet<Integer>
instances.