Reputation: 1
I am not sure what is wrong. I looked up other similar titled questions and answers on stack overflow but not sure what is wrong with my method. I am a beginner in java so any help would be great. Thank you.
My code is:
import java.util.*;
class LargestNumber {
static void printLargest(Vector<String> arr){
Collections.sort(arr, new Comparator<String>(){
@Override
public int compare(String X, String Y) {
String XY=X + Y;
String YX=Y + X;
return XY.compareTo(YX) > 0 ? -1:1;
}
});
Iterator it = arr.iterator();
while(it.hasNext())
System.out.print(it.next());
}
public static void main (String[] args) {
Scanner s=new Scanner(System.in);
int i,n;
n=s.nextInt();
Vector<String> arr;
arr = new Vector<>();
for(i=0;i<n;i++){
arr.add(s.next());
}
printLargest(arr);
}
}
error:
100
2 8 2 3 6 4 1 1 10 6 3 3 6 1 3 8 4 6 1 10 8 4 10 4 1 3 2 3 2 6 1 5 2 9 8 5 10 8 7 9 6 4 2 6 3 8 8 9 8 2 9 10 3 10 7 5 7 1 7 5 1 4 7 6 1 10 5 4 8 4 2 7 8 1 1 7 4 1 1 9 8 6 5 9 9 3 7 6 3 10 8 10 7 2 5 1 1 9 9 5
Your output:
Your stderr:
Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeLo(TimSort.java:777)
at java.util.TimSort.mergeAt(TimSort.java:514)
at java.util.TimSort.mergeCollapse(TimSort.java:441)
at java.util.TimSort.sort(TimSort.java:245)
at java.util.Arrays.sort(Arrays.java:1512)
at java.util.Vector.sort(Vector.java:1345)
at java.util.Collections.sort(Collections.java:177)
at LargestNumber.printLargest(LargestNumber.java:6)
at LargestNumber.main(LargestNumber.java:32)
Correct output:
9999999998888888888887777777776666666666555555554444444443333333333222222222111111111111111101010101010101010
(Time used: 0.12/1.50, memory used: 23568384/536870912.)`enter code here`
Upvotes: 0
Views: 846
Reputation: 2169
Problem is that your statement XY.compareTo(YX) > 0 ? -1:1
does not return 0 when two variables are equal, which is IllegalArgumentException: Comparison method violates its general contract!
From doc:
Parameters:
o1 - the first object to be compared.
o2 - the second object to be compared.
Returns: a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
Use following code to compare:
arr.sort((X, Y) -> {
String XY = X + Y;
String YX = Y + X;
return XY.compareTo(YX);
});
Upvotes: 2
Reputation: 129
What's happening is that you are entering
2 8 2 3 6 4 1 1 10 6 3 3 6 1 3 8 4 6 1 10 8 4 10 4 1 3 2 3 2 6 1 5 2 9 8 5 10 8 7 9 6 4 2 6 3 8 8 9 8 2 9 10 3 10 7 5 7 1 7 5 1 4 7 6 1 10 5 4 8 4 2 7 8 1 1 7 4 1 1 9 8 6 5 9 9 3 7 6 3 10 8 10 7 2 5 1 1 9 9 5
with spaces. When that happens, the input gets treated like a one string without another string to compare to, which is why you got IllegalArgumentException. To fix this code, change your for loop in your main method like this...
for(i=0;i<n;i++){
arr.add(String.valueOf(new Random().nextInt(17)));
}
Upvotes: 0