Questions tagged [comparable]

In Java, this interface is implemented by a class to indicate that it can be compared to another object and therefore ordered. In Go, comparable is a predeclared interface constraint for generic types that support == and != operators. Make sure to use the appropriate language tag along with this.

Filter by
Sorted by
Tagged with
0 votes
2 answers
56 views

How to make an arraylist of string sorted by the second character

I want to sort an arrayList of String to be sorted by the second character and using the comparable interface and CompareTo method. public class Main implements Comparable<String>{ public ...
Vikki's user avatar
  • 23
0 votes
0 answers
33 views

Internal working of timsort and compareTo() method in Comparable interface

I have been looking at different articles on internet and everyone mentions that compareTo() method would follow natural ordering by default. Let's taken an example. class Car implements Comparable<...
Rakesh .p's user avatar
0 votes
0 answers
15 views

How to call the generic comparable in a AVL Tree descendants class?

I am attempting to create a AVL Tree implementation. I am working on a method to ocunt the descendants of a node. I also use the comparator. public class AVLTree<E extends Comparable<E>> ...
Matthew Benfield's user avatar
-2 votes
2 answers
84 views

How to compare two different generic instantiations of a class in Java?

MRE because well, assignment... sigh This is the problem I'm stuck on: Consider the following class: class MyClass<T extends Comparable<T>> implements Comparable<MyClass<T>> { ...
kesarling He-Him's user avatar
1 vote
2 answers
63 views

Best way to deal with some classes implementing comparable and some not in a Binary search tree

I am looking for suggestions on how to handle some possible elements implementing comparable and some not. I am currently trying to do it like this class BinaryTree<E> { private Comparator<...
JoPoLu's user avatar
  • 21
0 votes
1 answer
136 views

invalid operation: v > max (type parameter T is not comparable with >) [duplicate]

package main import ( "fmt" ) func findMinMax[T comparable](arr []T) (min, max T) { for _, v := range arr { if v > max { max = v } else if v < min ...
twentyfourk's user avatar
0 votes
1 answer
28 views

Sorting in java using lambda Expression

class Solution { public int[] Sort(int[] nums) { int[] arr = {1, 2, 3, 4, 5}; Arrays.sort(arr, (a, b) -> (a+""+b).compareTo((b+""+a)));//this part is showing ...
Mohammad Basheer's user avatar
-1 votes
2 answers
60 views

JAVA Collections Modified Sorting

List<Integer> list = new ArrayList<>(); for(int i = 0 ; i <= 8 ; i ++){ list.add(i+1); } Collections.sort(list,(a, b)-> (a%b==0) ? 1 : (a%b==1) ? -1 : 0 ); list.forEach(System.out::...
Abhishek Pandey's user avatar
0 votes
0 answers
513 views

4.15.5 Fraction is Comparable Java CodeHS

I am trying to implement a Comparable interface in a Fraction class that I coded for an exercise problem in CodeHS. The objective of the code is to compare two fractions and determine whether they are ...
Sumlina Alam's user avatar
-2 votes
1 answer
59 views

Java TreeMap with custom class (Long, Date) as Key to sort by Date, but put/get by Long

I have a specific problem. I need to create a map of objects identified by a custom Index class consisting of two fields: Long id and Date date. Is it possible to make TreeMap sorted by the date field,...
Nolias's user avatar
  • 101
0 votes
1 answer
59 views

How to order a list of objects as per custom order guidelines? [duplicate]

data class User( val name: String, val address: Address, val group: String ) data class Address( val street: String, val city: String ) I have a list of users. I need to order ...
AndroidDev's user avatar
2 votes
1 answer
79 views

How, with Ruby, can I access and compare these nested array values?

I have this nested array: [[1, 2, 3], [1, 3, 6], [1, 4, 12], ...
jbk's user avatar
  • 1,930
2 votes
0 answers
42 views

How to use generics that implements comparable

I am very confused about something in java. So the project I was given is write stacks in java, and the program begins with public class Stack<T extends Comparable<? super T>>. However, ...
Je-Yu Chou's user avatar
1 vote
3 answers
474 views

find the matching objects from two array lists? list can contain same multiple objects

I have two list ListA listA = new ArrayList() and ListB listB = new ArrayList() both contain object of type Position object and Position contain these variables. Position { String account; ...
Enthu Leo's user avatar
1 vote
1 answer
43 views

How to compare two properties of a class

There is a class Movie which has two properties, id and type. static class Movie implements Comparable<Movie> { Integer id; Type type; Movie(Integer id, Type type) { this.id ...
user10608855's user avatar
-2 votes
1 answer
91 views

Compare arrays of custom objects in Swift?

I have objects which implement Сomparable protocol: class SomeClass: Comparable { ...//comparable implementation } So now I can for example sort [SomeClass]. But if I want to compare arrays of ...
Gargo's user avatar
  • 1,180
0 votes
2 answers
66 views

How can I implement a PriorityStack that accepts objects with the Comparable interface?

I took a look at the code in this thread: https://codereview.stackexchange.com/questions/98105/priority-stack-in-java This implements a PriorityStack using the object and the priority. I need an ...
JDausyd's user avatar
  • 17
0 votes
1 answer
32 views

Generic Comperable Type Java - Error if I set the function to static

Good evening, something quirky is going on with Java. I'll be the first to admit that I suck at Java, but I really can't wrap my head around this one, maybe someone can help. I'm trying to make a ...
ETisREAL's user avatar
  • 122
3 votes
1 answer
41 views

How can multiple static methods use the same generic type?

While learning from Algorithms (4th edition) (by Robert Sedgewick; Kevin Wayne), I am trying to recreate their codes. They have raw uses of parametrized constructors (generics) which I assume might be ...
Aman's user avatar
  • 43
1 vote
1 answer
66 views

Creating generic comparator for List<List<Comparable>>

I'm trying to create a generic comparator for a List<List<Comparable>> which can sort on multiple fields. The structure represents a List of rows and within each row, I want to sort on ...
Peter Kronenberg's user avatar
0 votes
4 answers
96 views

Comparable custom types which can be sorted as array items without defining an additional compare function inside sort()

Languages such as Python and Java have special methods for sorting custom classes. In JavaScript, toString() can be overridden, but this does not work easily for numeric values. As a workaround, I ...
Jim K's user avatar
  • 13k
0 votes
0 answers
46 views

How to search for given word or character in ArrayList and show those who match and sort them

I'm still new to java. My task was to find all Producers in ArrayList who matches the word or character that the user inserts and return a list of those words sorted by their field. For example, we ...
sarah6's user avatar
  • 28
8 votes
1 answer
555 views

Ensure strict comparability at compile time in Go 1.20?

In Go 1.18 and Go 1.19 I can ensure at compile time that a type is strictly comparable, i.e. it supports == and != operators and those are guaranteed to not panic at run time. This is useful for ...
blackgreen's user avatar
  • 36.2k
0 votes
0 answers
1k views

Receiver class does not define or inherit an implementation of the interface java.lang.Comparable

I have been stumped on this issue for quite a while. Could not find anything wrong with my code online, everything regarding structure seems correct. Spits out error message: "Receiver class ...
DrDallas's user avatar
-1 votes
1 answer
117 views

How to solve problem with Java TreeMap when you use object as key? [closed]

package RecyclingJava.recycling; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.TreeMap; public class ...
Nemesis96's user avatar
0 votes
0 answers
35 views

How do I get the max value in this example?

For example this is how I would get the max here public static <T extends Comparable<T>> T max(T x, T y, T z) { T max = values; if (y.compareTo(max) > 0) { ...
meownster's user avatar
0 votes
0 answers
29 views

Optimization and construction of a red-black tree if the comparator of the key is not overridden

How is the optimization and construction of a red-black tree inside the HashMap Bucket if the comparator of the key is not overridden? Here is what I found on the subject: HashMap can contain keys of ...
zahaand's user avatar
  • 21
1 vote
2 answers
172 views

Dijkstra's weighted shortest path in Python

I'm trying to solve a question from PepCoding, Graph Foundation 1, Shortest Path In Weights, and replicating the solution from Java to Python. Question: 1. You are given a graph and a source vertex. ...
imeanup's user avatar
  • 11
0 votes
1 answer
242 views

Problem with overriding compareTo method in subclass

I am creating subclass and have some class elements inside it. Now I want to override compareTo method from super class and use variables from subclass as argument in new compareTo method but I get ...
yowkarii_3's user avatar
1 vote
0 answers
35 views

What could cause a generic Comparator (or Comparable) to have significantly worse performance than a non-generic one?

I have an implementation of the A* pathfinding algorithm, defined to operate over anything that implements the following interface: public interface Pathable<N extends Pathable<N>> extends ...
Retzinsky's user avatar
2 votes
2 answers
57 views

method cannot be applied to given types when trying to perform a generic binary search

Let's say I have a class called RandomObject: public class RandomObject implements Comparable<RandomObject> { private String name; private int value; public RandomObject(String ...
douglasdotv's user avatar
-1 votes
1 answer
73 views

How to use a Function<T, R> as parameter in method

I'm learning Java lambdas for school, and I am stuck for a couple of days now. Background I have a list of pumps which I have to sort out on power, last revision, … I already wrote a Comparator that's ...
S.Cl's user avatar
  • 1
-3 votes
2 answers
118 views

How do sort Entries of the Map<Type,List<String>> by Value and store into a LinkedHashMap

I have the following Item class: @AllArgsConstructor @Getter public static class Item { public enum Type { Meat, Fish } private String name; private int price; private Type type; } ...
Mark Skylarkxx's user avatar
3 votes
1 answer
385 views

Unable to implement Comparable interface on Kotlin Enum

I would like my Enum values to be comparable with other types, for instance, String. I am not entirely sure why it complains and what the error means. enum class Fruits(val value: String): Comparable&...
Arturs Vancans's user avatar
0 votes
1 answer
58 views

use compareTo on more specific Comparables in Java

I would like to have a more specific Comparable interface so that I can type return parameters better. The interface currently looks like this: public interface SpecialComparable<T extends ...
Mai65's user avatar
  • 93
-2 votes
2 answers
834 views

prog.java:59: error: incompatible types: bad return type in lambda expression ((p1,p2)->(p2.ratio-p1.ratio));

I am trying to make a priority Queue which contains pair of double and integer types but I am getting this error : -> error: incompatible types: bad return type in lambda expression PriorityQueue ...
Hemant Srivastava's user avatar
0 votes
3 answers
306 views

Could java enum class implements "Comparable" interface?

Seems that enum class already has a final compareTo function, which cannnot be overriden. But my requirement is to customize an enum class like this: enum Operator { Add('+', 1), Sub('-', 1), ...
Troskyvs's user avatar
  • 7,617
-3 votes
2 answers
78 views

Comparable<Integer> array comparison java [closed]

I'm tasked with writing mergesort in java, the task also specified I can't use integers, I have to use Comparable integers. This is my first time using java. My problem is comparing elements in two ...
Nuh's user avatar
  • 1
-2 votes
1 answer
59 views

Collections.sort() doesn't work. Problem with implementing the Comparable<> interface

Does someone have an idea why this code doesn't sort the employees properly? I need them to be sorted in ascending order by the amount of their salary. I think I've messed up smth cause I'm storing ...
Alexander's user avatar
1 vote
2 answers
2k views

ThreadPool throws java.util.concurrent.FutureTask cannot be cast to java.lang.Comparable

I've got a very simple program: public static void main(String[] args) throws Exception { class MyThread2 implements Runnable{ @Override public void run() { ...
Immanuel Kant's user avatar
0 votes
2 answers
124 views

Sorting an array of zeros, negative and positive numbers with Comparable interface

class pair implements Comparable<pair>{ int x, y; pair(int x, int y){ this.x = x; this.y = y; } public int compareTo(pair c){ return this.y-c.y; }} class Solution { public int ...
Anand Sharma's user avatar
0 votes
0 answers
59 views

Code is not executable because of "the type MyComparator1 already exists" error

In the code below I am trying to use Comparable and Comparator Interfaces for Default and Customized Sorting on my own defined Employee class respectively. But i get an error near the class "...
PranjalTech's user avatar
2 votes
4 answers
6k views

Java Stream: Class com.java8.Student cannot be cast to class java.lang.Comparable

I'm iterating all Student data using natural sorting method of java 8 sorted(). While iterating student data, get exception in IDE console class com.java8.Student cannot be cast to class java.lang....
Faheem azaz Bhanej's user avatar
0 votes
2 answers
78 views

As per TreeSet two objects are shown equal but Queue shows them as unequal

I have the follwing Person Class - Person.java - public class Person implements Comparable<Person> { private int id; private String name; Person(int id, String name) { this....
Payel Senapati's user avatar
0 votes
1 answer
39 views

Unable to understand the logic behind treesorting in this particular case of mine

I have the following "Person" class - import java.rmi.activation.ActivationGroup_Stub; public class Person implements Comparable<Person> { private int marks; private String ...
Payel Senapati's user avatar
1 vote
1 answer
170 views

Generic method with Comparable does not accept Integer[]

Problem I have a class called public class HeapClass <E extends Comparable <E>> There is a method in there called public void heapSort(E[] arr) I have a small main method to test it out ...
Brian O's user avatar
  • 109
2 votes
3 answers
2k views

Difference between Collections.sort(list) and Collections.sort(list,comparator)

What's the difference between: public FlyingRabbit(){ list = new ArrayList<Sellable>(); } public void sort(Comparator<Sellable> comp) { Collections.sort(list, ...
Nooboolean's user avatar
1 vote
2 answers
379 views

When should I use Comparator vs Comparable?

I have a list of POJOs I need to sort somehow. I define a Comprator inside the POJO class and use it to sort the list. Is the following way correct/best practice? Is there a better way to do it? ...
cloooze's user avatar
  • 163
1 vote
1 answer
256 views

Using comparable in a method in the main method

I am trying to check the values of a comparable method and assign the 1 and -1 value to true and false. I made a simple if else statement that does just that but I want to make it inside of a method ...
uhhsoup's user avatar
  • 11
0 votes
1 answer
305 views

How do I make an array of Comparables

I am trying to make arrays of objects that implement the Comparable interface. The object of the project is to merge two presorted arrays, of Comparable type, into a single sorted array. So far I have:...
Devon Goshorn's user avatar

1
2 3 4 5
26