"Comparison Method violates its general contract" - even with correct implementation of comparator - comparator

I have some problem with the collection.sort() method.
java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeLo(TimSort.java:747)
at java.util.TimSort.mergeAt(TimSort.java:483)
at java.util.TimSort.mergeCollapse(TimSort.java:410)
at java.util.TimSort.sort(TimSort.java:214)
at java.util.TimSort.sort(TimSort.java:173)
at java.util.Arrays.sort(Arrays.java:659)
at java.util.Collections.sort(Collections.java:217)
this is my comparator
public int compare(Key key1, Key key2)
{
if (key1.Score > key2.Score)
return -1;
else if(key1.Score < key2.Score)
return 1;
else
return 0;
}
I am currently jdk 1.7, i tried with 1.6 also but it did not work. I am not able to understand whether it is the problem with sort method or some other issue.( I am trying to sort a list with more than 1000 items and it does not have any NaNs).

Violating the general contract of a comparison method means that it does not provide a consistent or correct answer. It seems this method does not return the same result while comparing the same objects for several times.
This code works fine as a standalone version. Do you have some other threads modifying the collection items?

Related

Kotlin Reflection - Check if property has type

I want to iterate over all fields in one of my classes, filter for annotated ones and then check if the field has one specific type.
All I found was field.returnType.isSubtype(other: KType) but I don't know how to get the KType of my other class.
Here is my code so far:
target.declaredMemberProperties.forEach {
if (it.findAnnotation<FromOwner>() != null) {
if ( /* it.returnType is Component <- Here I need some working check */ ) {
// do stuff
} else {
// do ther stuff
}
}
}
There are at least two solutions here:
Get the KClass<*> of it.returnType using .jvmErasure, then check the subtype relationship for the KClasses:
it.returnType.jvmErasure.isSubclassOf(Component::class)
Since Kotlin 1.1, you can construct the KType from the KClass token using .createType() (check its optional parameters: you can use them to provide nullability info, type arguments and annotations), and then check the subtype as you suggested:
it.returnType.isSubtypeOf(Component::class.createType())
Creating the type on every iteration may introduce performance issues, make sure you cache it if you need it often.

Collection intermediate operations library in Java7

I Like the idea of intermediate operations of Java8, Where all operations will applied once when a terminal operation is reached.
I am asking is there library that I can use with Java 7 that allow me to achieve such behaviour.
Note:
I am using commons-collections4 for collection operations, like forAllDo, So it is possible to use it for such case? (intermediate vs terminal operations)
Guava
As your [Guava] tag suggests, most Guava collection operations are lazy - they are applied only once needed. For example:
List<String> strings = Lists.newArrayList("1", "2", "3");
List<Integer> integers = Lists.transform(strings, new Function<String, Integer>() {
#Override
public Integer apply(String input) {
System.out.println(input);
return Integer.valueOf(input);
}
});
This code seems to convert a List<String> to a List<Integer> while also writing the strings to the output. But if you actually run it, it doesn't do anything. Let's add some more code:
for (Integer i : integers) {
// nothing to do
}
Now it writes the inputs out!
That's because the Lists.transform() method doesn't actually do the transforming, but returns a specially crafted class which only computes the values when they are needed.
Bonus proof that it all works nicely: If we removed the empty loop and replaced it with e.g. just integers.get(1);, it would actually only output the number 2.
If you'd like to chain multiple methods together, there is always FluentIterable. That basically allows you to code in the Java 8 Stream-like style.
Goldman Sachs Collections
While Guava usually does the right thing by default and works with JDK classes, sometimes you need something more complex. That's where Goldman Sachs collections come in. GS collections give you far more flexibility and power by having a complete drop-in collections framework with everything you might dream of. Laziness is not theer by default, but can be easily achieved:
FastList<String> strings = FastList.newListWith("1", "2", "3");
LazyIterable<Integer> integers = strings.asLazy().collect(new Function<String, Integer>() {
#Override
public Integer valueOf(String string) {
System.out.println(string);
return Integer.valueOf(string);
}
});
Again, doesn't do anything. But:
for (Integer i : integers) {
// nothing to do
}
suddenly outputs everything.

Flex How To Call A Function With A Variable Number Of Parameters?

Let's Say I Have This Class:
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
trace(getAverage(1,2,3));
trace(getAverage(1,2,3,4));
trace(getAverage(1,2,3,4,5));
}
public function getAverage (...numbers) {
var total = 0;
for (var i = 0; i < numbers.length; i++) {
total += numbers [i];
}
return total / numbers.length;
}
}
}
How do I accomplish the "opposite" of this? Namely, how could I now CALL 'getAverage' with a dynamic number of paraemters?
For instance, if I wanted to do something LIKE:
var r:int=Math.random()*6;
var a:Array=new Array();
for (i:int=0;i<r;i++) {
a[i]=Math.random()*22;
}
// Now I have 'r' Number Of Parameters Stored In 'a'
// How Do I Call getAverage, with all the values in 'a'??
// getAverage(a) isn't right, is it?
// I'm looking for something similar to getAverage(a[0],a[1],a[...]);
var av:Number=getAverage(???);
What I want to know, is if I have a function that takes a variable number of arguments, that's great, but how can I CALL IT with a variable number of arguments, when that number isn't known at runtime? Possibly it's impossible... I'm just not sure, since 'callLater' seems to be able to take an array and generate a dynamic number of parameters from it somehow...
NOTE: Answers consisting solely of "Why Do You Want To Do This?", will be downvoted.
P.S. This IS NOT about calculating Averages! I REALIZE There Are Way Simpler Ways Of Doing All Of This! (I could just write getAverage to accept a single array as its only parameter) The Above is just an EXAMPLE to Illustrate my Question. HOW TO PASS A DYNAMIC NUMBER OF PARAMETERS TO A FUNCTION?
Is this what you're looking for?
var av:Number = getAverage.apply(null, a);
Dave is correct. You can use the apply method of a function to pass in an Array of arguments.
Here is a better explanation of how it works and what the arguments of apply are:
http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/Function.html
Also note that you can use the call method to do the same thing but using ...args (comma-delimited list) instead, but apply would be more suitable to your situation.
The problem with your question is that the arguments object is already an Array and using (...args) already provides you with a dynamic way to pass any number of arguments you require. Sorry about the previous answer, wasn't thinking straight...
You can create an array or an object with those parameters and pass that object to that function. That's just normal.
Flash has a rather strong introspection capabilities. So, instead of passing a number of objects, you just pass a single dynamic object with any number of attributes you need:
var ob:Object={arg1:"value1", arg2:8};
var arg:String="arg4";
ob["arg3"]=8;
ob[arg]=18;
trace (ob.hasOwnProperty("arg1"));
trace (ob.arg3);
trace (ob.arg4);
That should cover just about any use case you might need. The downside is that this allows for some rather clever and hard to trace bugs. :-)

Testing an object's state at save

I'm looking to write unit tests for a method such as this one:
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
ISPMembershipUserDao userDao = GetISPMembershipUserDao();
if (ValidateUser(username, password))
{
SPMembershipUser user = userDao.GetUserByUserName(username);
user.PasswordQuestion = newPasswordQuestion;
user.PasswordAnswer = newPasswordAnswer;
userDao.Save(user);
return true;
}
return false;
}
It's a fairly straight-forward method to test. I'm using the Rhino Mocks framework. But one aspect has me questioning myself. I stub the DAO object and its save method, and I'm wondering how deeply I should test that user object that is passed to the save method. Should I assert that every property of that object is as I expect it to be? Or should I only assert that the PasswordQuestion and PasswordAnswer properites have the correct values? The former seems right to me, as I should make sure that only those two properties have been modified, and the others haven't been touched.
I was hoping some people could give their opinions on this. Is there a rule of thumb or pattern to keep in mind for these types of situations?
Warning: personal opinion ahead
Ok, now that that's out of the way.... for me, it comes down to what I need to do to feel that my code properly implements the needed logic. In this case? I'd have two test cases:
Dealing with ValidateUser returning false
Should return false
Save should not have been called
Dealing with ValidateUser returning true
Should return true
Save should have been called
Object passed to save has the modified question and answer
No checks of other properties on user object
However, if/when I got a bug filed that affected this part of the code, I'd add whatever (initially failing) tests were needed to cover the bug, fix the bug, and leave the tests.
Since it's so easy to set up a constraint here, why not test it to ensure there are no side-effects to your method?
stubbedUserDao.AssertWasCalled(x => x.Save(null), o => {
o.IgnoreArguments();
o.Constraints(Property.AllPropertiesMatch(expectedMatchingUser));
});

what is the flex (ActionScript3) syntax for a function valued function's type?

What is the syntax to declare a type for my compare-function generator in code like the following?
var colName:String = ""; // actually assigned in a loop
gc.sortCompareFunction = function() : ??WHAT_GOES_HERE??
{
var tmp:String = colName;
return function(a:Object,b:Object):int { return compareGeneral(a,b,tmp); };
}();
Isn't "Function" a data type?
In order to understand what the data type is, we must know what the intended outcome of the return is. I need to see the code block for compareGeneral, and I still don't believe this will help. You have two returns withing the same function "gc.sortCompareFunction", I believe this is incorrect as return gets a value and then acts as a break command meaning the rest of the anything withing the same function block is ignored. The problem is that I don't know which return is the intended return, and I don't know that flash knows either. You can use * as a data type, but this should only really be used in specific situations. In this situation I believe you need only the one return value that merely returns whatever the value of compareGeneral.
Now if this is a compareGenerator it really should either return a Boolean TRUE or FALSE, or a int 0 or 1, lets use the former. Also I believe we can use one less function. Since I have not seen all of your code and I am not exactly sure what your trying to accomplish, the following is hypothetical.
function compareGeneral(a:object,b:object):Boolean
{
//Check some property associated to each object for likeness.
if(a.someAssignedPropery == b.someAssignedPropery)
{
return true;
}
return false;
}
var objA:Object = new Object();
objA.someAssignedProperty = "AS3";
objB.someAssignedProperty = "AS3";
compareGeneral(objA,objB);
In this case compareGeneral(objA,objB); returns true, though we haven't done anything useful with it yet. Here is a way you may use it. Remember that it either returns a value of true or false so we can treat it like a variable.
if(compareGeneral(objA,objB)) //same as if(compareGeneral(objA,objB)) == true)
{
trace("You have found a match!");
//Here you can call some other function or set a variable or whatever you require functionality wise based on a match being found.
}
else
{
trace("No match could be found!");
}
I hope that this is able to help you understand data types and return values. I do not know what you were doing with tmp, but generally functions that return a value deal with that one thing and only that thing, so it is best that the compare function compare one thing against the other and that be the extent of the call. Whatever functionality you require with tmp can go inside its own function or method, and be called when needed.

Resources