compareto

Comparison method violates its general contract! Java 7 only

非 Y 不嫁゛ 提交于 2019-11-26 12:25:46
问题 I know this has been an issue for a while now, and checked all previously answers I could get, but still this one doesn\'t work. The object \'crew\' represents crewmembers with ranks and other items. The comparison should be made by comparing \'assigned_rank\', an int value, and if this value is equal in both instances, then \'is_trainer\', a boolean, should make the difference. This method worked great as long as it was running with java < 7. But since Java 7 I keep getting this one: java

How to simplify a null-safe compareTo() implementation?

依然范特西╮ 提交于 2019-11-26 08:44:24
问题 I\'m implementing compareTo() method for a simple class such as this (to be able to use Collections.sort() and other goodies offered by the Java platform): public class Metadata implements Comparable<Metadata> { private String name; private String value; // Imagine basic constructor and accessors here // Irrelevant parts omitted } I want the natural ordering for these objects to be: 1) sorted by name and 2) sorted by value if name is the same; both comparisons should be case-insensitive. For

How to sort an array of objects containing null elements?

情到浓时终转凉″ 提交于 2019-11-26 08:36:53
问题 In my program an array fClasses of fixed length [7] of objects is created, each object is a class FClass that contains 3 Strings , an int , and an int[] . These values are read from a .txt file and added to a specific index of the array based on the value of the int . There are less entries in the .txt file then there are indices in the array so the array ends up looking something like this: fClasses[0] { str1, str2, str3, int1, int [] {1,2,3,4,5}} fClasses[1] { str1, str2, str3, int1, int []

BigDecimal equals() versus compareTo()

天大地大妈咪最大 提交于 2019-11-26 05:21:52
问题 Consider the simple test class: import java.math.BigDecimal; /** * @author The Elite Gentleman * */ public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub BigDecimal x = new BigDecimal(\"1\"); BigDecimal y = new BigDecimal(\"1.00\"); System.out.println(x.equals(y)); System.out.println(x.compareTo(y) == 0 ? \"true\": \"false\"); } } You can (consciously) say that x is equal to y (not object reference), but when you run the program,