FAQ Database Discussion Community


Split off logic in methods when custom Comparator is provided or elements implements Comparable?

java,collections,comparator,comparable
What is The best practice to split off logic in methods , who will work with Comparable elements, or specific Comparator is provided at creation time, depending on which constructor of the class is used? Example: public class MinMax<E> { private final Comparator<? super E> comparator; private final boolean isSpecificComparatorProvided;...

Use known methods of generic objects

java,generics,comparable
I'm having a class receiving 2 unknown, generic Objects x and y. I have to compare these to objects if they are comparable. I figured out that I can check if the Objects implements the Comparable interface by using instanceof, but I don't know how I can use the .compareTo...

Java interface to compare various data types

java,comparison,comparable
I need to have an interface that will allow this to work for all data types if implemented with generics. Something to this effect. if (myIter.myDataType < SearchDataType){ return myIter; } or if (myIter.compareTo(SearchDataType)){ return myIter; } needs to work with integers, char, strings and even Boolean if possible. I'm...

Does PriorityQueue maintain natural order? [duplicate]

java,collections,queue,priority-queue,comparable
This question already has an answer here: Print content of priority queue[java] 1 answer The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. However, in the following example, when I...

Optimal median function

java,comparable
I was experimenting with some code in an attempt to answer Generic Method to find the median of 3 values and was trying to ensure that the compareTo method was called a minimum number of times and to maximise the efficiency of the code and came up with this: //...

Using comparable to compare different variables

java,libgdx,comparison,comparator,comparable
I'm familiar with standard comparisons using the Comparable interface, although today I'm having some trouble when I want to compare several different variables. I basically want to implement a compareTo method that yields the result -1 only when the following if statement is true: if (o.maxX > minX && o.maxY...

Creating a Generic for a Class

java,class,generics,comparable
Assuming you have a class named Rational where each object contains two ints representing the numerator and the denominator, write the class definition line if you wanted to indicate that it would implement the generic interface Comparable and write the body of the required method with the signature: public int...

Greater Than Operator Undefined on Generic Type, Despite extending and implementing Comparable

java,comparable
I searched and found several instances of similar problems but the obvious solutions have already been implemented, so I'm at a bit of a loss. FYI: This is a homework assignment, if it matters. public class Entry<K extends Comparable<K>, V> implements Comparable<Entry<K, V>> { protected K key; protected V value;...

Java: Uniform Cost Search with Node class

java,graph-algorithm,priority-queue,comparable
The below code is supposed to detect an image, create a 2d array containing the pixel values from that image, and determine the path of lowest cost (I used Uniform Cost Search) from a Point A inside the image to a Point B inside the image. When I run my...

Java Generics: compareTo and “capture#-of ?”

java,generics,binary-tree,comparable
I'm trying to write an implementation of a BinaryTree whose object can be of any type that implements Comparable. However, I realize that won't completely work. For example, A String and a Double wouldn't be able to be inserted into the same tree, even though they both implement Comparable. So,...

Bound Mismatch : Generic class (of a Generic class extending Comparable (of a Generic class extending Comparable))

java,generics,comparable
I know it sounds confusing, but that's the best I could explain. (You can suggest a better title). I have 3 classes:- A public class A <T extends Comparable<T>> { ... } B public class B { A<C> var = new A<C>(); // Bound mismatch: The type C is not...

Contracts of the compare and compareTo method from Comparator and Comparable

java,comparator,comparable
When implementing the Comparator and Comparable interfaces, is it required to ensure that: If x.compare(Object obj1, Object obj2) == x.compare(Object obj3, Object obj2) or obj1.compareTo(obj2) == obj3.compareTo(obj2) , then obj1.equals(obj3) must be true?...

Using Comparable? java,oop,collections,comparable
I am working on existing code. In the code a list of objects is being created then Collections.sort and Collections.reverse are used on this list. Here is a small example of the class they wanted to be comparable: public class Student implements Comparable<Student> { public int compareTo(Student s) { //code...

In Ruby (1.9.3), why does nil respond to the comparison operator, `<=>`?

ruby,null,comparable
To me, a null type being compared to anything else (even another null type) is an undefined operation. Please correct me if I'm wrong there. Under that assumption, the following makes sense to me: nil.is_a? Comparable => false nil.respond_to? :<= => false nil.respond_to? :< => false nil.respond_to? :>= => false...

“Comparison method violates its general contract!”, everything seems OK

java,collections,compare,comparator,comparable
I am aware of the compare rules in Java (and in general) as described here. I have an ArrayList of Strings. Each String represent a Texas Hold'em Poker Hand ignoring the suit. Each String is exactly 13 characters long. Each String consists of digits only whose sum is 7. For...

Comparable and (MyClass)null

java,nullpointerexception,null,compare,comparable
Say I have public class MyClass implements Comparable<MyClass> { public int compareTo(MyClass mc) { //<implementation ommited>... } } The docs for Comparable say that "The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value...

Why object of number can be added in TreeSet

java,collections,wrapper,comparable
The object of class which we want to add into TreeSet, that Class must implement Comparable interface But Number class does not implement Comparable then how TreeSet allow Number to get added. Number n1= 11; Number n2= 12; Number n3= 13; Set<Number> set = new TreeSet<>(); set.add(n1); set.add(n2); set.add(n3); ...

remove item from comparable array

java,arraylist,comparable
I'm very new to java and my first question is what is this Comparable thing? and in my sample code, why Class Bag<T extends Comparable<T>>?? What's the purpose? My second question is how to remove an item from this Comparable array. I have wrote the removeMin method, I have found...

Make java class Comparable to 2 different Classes

java,class,comparable
I would like to implement the Comparable Interface "Twice" public class Segment implements Comparable<Segment,Point>{ @Override public int compareTo(Segment o) { return 0; } @Override public int compareTo(Point p) { return 0; } Is it possible in some way? (Without using the generic interface compareTo(Object o) i think it's nasty...)...

What is point of implementing comparable Custom Class?

java,comparable
I dont get the point of implementing that class since i cannot use comparison as "<,=,>" in anywhere in code. I have to use it with compareTo method. So i can write my own function like isEqual or bigger which returns boolean unlikely of compareTo method. Am i missing something?...

Max element in a 2 dimensional array using generics

java,sorting,generics,multidimensional-array,comparable
I have all my code completed and I can't for the life of me figure out why when I run this that the max element is 5 and not 6. Any help is gratefully accepted. public class MaxElement2DimArray { public static void main(String[] args) { Integer[][] numbers = { {1,...

when to implement comparable and when to implement equals in Java

java,equals,hashcode,comparable
In Java, when should I implement Comparable<Something> versus implementing the equals method? I understand every time I implement equals I also have to implement hash code. EDIT Based on answers I am getting below: Is it safe to say that if I implement Comparable then I don't need to implement...

what does “other” mean in Java?

java,object,interface,comparable
I have this code, but I fail to understand what "other" actually is, and what it's trying to do. public interface Comparable<T> { int compareTo(T other); } What is they parameter "other" supposed to mean?...

What is the difference between these class declarations with Comparable?

java,generics,tree,comparable,generic-programming
Here is one declaration public class BinarySearchTree<AnyType extends Comparable<? super AnyType>> { .... } Here is the other declaration public class BinarySearchTree<AnyType extends Comparable<AnyType>>{ ..... } I know the first declaration is preferred(seen it in alot of java examples and textbooks) but why is that? All my code ran fine...

Working of == in the Comparable interface used in ArrayList

java,collections,comparable
Working of == operator in Comparable Interface Employee.java class Employee implements Comparable { int id; String name; int age; Employee(int id,String name,int age) { this.id=id; this.name=name; this.age=age; } public int compareTo(Object obj) { Employee emp = (Employee)obj; if(age==emp.age) { return 0; } //else if(age>emp.age) //return 1; else return -1; }...

Comparing Generics that are comparable in Java

java,generics,compare,comparable
I have a Generic Binary Tree that will add objects lessThan or equalTo to the left, and objects greater than to the right. My problem is with the comparing the Generics, I know the data value will be a object-wrapped primitive or a String, so they are comparable. But, I...

Java type parameter is not within its bound

java,generics,comparator,comparable
I have a class Zeitpunkt which implements a date with time and in addition a class Suchbaum which represents a binary search tree. I want to use a Comparator-Object in Suchbaum to sort a tree by the day of Zeitpunkt, but when I want to create a Suchbaum object, it...

Implement BST using comparable or comparator

java,comparator,comparable
I'm trying to create a generic BinarySearchTree<T> class. I want to provide two options (constructors), Empty constructor for a generic class which implements Comparable<T> i.e. If Dog is a class which implements Comparable<Dog>, then: BinarySearchTree<Dog> bst = new BinarySearchTree<Dog>(); Pass a Comparator<T> for a generic class which need not have...