Help needed with Comparator objects and Collections
I'm having issues with using Comparator objects and Collections and would be grateful to receive assistance on the following:
Quote:
Write code for a Comparator object that orders List<Integer> objects in order of their length. Then write code for a Comparator object that orders List<Integer> objects in the order of the sum of their integers (the sum is all the integers in the list added together). Use these Comparator objects and the two-argument method max from Java’s class Collections to find the longest list and the list which adds up to the most from the set of lists from a HashSet<List<Integer>> object, for example as created in question 2.
The following is the code that I already have (to summarise it's consists of a HashSet<List<Integer>> object that will store values of type List<Integer>, I'm at the point now where I need to re-order the HashSet and then run both Comparators):
Code :
import java.util.*;
class Ex5b implements Comparator<HashSet<List<Integer>>>
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String line, ask;
boolean run = true;
HashSet<List<Integer>> hs = new HashSet<List<Integer>>();
while(run)
{
System.out.println("Enter some integers (all on one line):");
line = in.nextLine();
String[] words = line.split(" ");
List<Integer> l = new LinkedList<Integer>();
for(int i=0; i<words.length; i++)
{
l.add(new Integer(words[i]));
}
hs.add(l);
System.out.println("Would you like to enter more integers?: (y/n)");
ask = in.nextLine();
if(ask.equalsIgnoreCase("N"))
{
run = false;
}
}
System.out.println("Contents of list: " + hs);
//PLACE WHERE I AM STUCKFOR REST OF CODE
}
// ATTEMPT TO CREATE A COMPARATOR THAT WOULD SORT HASHSET IN ORDER OF LENGTH OF EACH LIST
public HashSet<List<Integer>> compareLength(HashSet<List<Integer>> hs)
{
HashSet<List<Integer>> hsLength = new HashSet<List<Integer>>();
// INCOMPLETE - I PRESUME THAT THIS SHOULD BE DONE CONSTRUCTIVELY AND NOT DESTRUTIVELY - ALSO MEANS RETURNING A HASHSET WHICH I AM HAVING PROBLEMS WITH (NON-STATIC METHOD BEING REFERENCED FROM A STATIC CONTEXT)
}
}
INTERFACE FOR COMPARATOR(S)
Code :
import java.util.*;
interface Comparator<T>
{
public T compareLength(T o1);
}
// I PRESUME I WILL REQUIRE ANOTHER METHOD FOR ORDERING BY SIZE HERE
I'd be grateful if anyone could assist me as I've been working on this on/off over the last couple of days and are completely lost...
Re: Help needed with Comparator objects and Collections
What method of what class are you using that requires a Comparator object?
Re: Help needed with Comparator objects and Collections
Oh would I require another class that contain a method which would run the comparators?
I'm pretty new to using Interfaces if the case...
Thanks for replying.
Re: Help needed with Comparator objects and Collections