D
D
Den4_x2019-07-28 19:13:46
Java
Den4_x, 2019-07-28 19:13:46

Why doesn't the Comparable interface work?

package WorkSpace;
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.lang.Math;
import java.util.*;


public class WorkSpace { 
    public static void main(String args[]){ 
        TreeSet<Sticks> box1 = new TreeSet<Sticks>();
        
        Sticks obj1 = new Sticks(19);
        Sticks obj2 = new Sticks(9);
        Sticks obj3 = new Sticks(53);
        
        box1.add(obj1);
        box1.add(obj2);
        box1.add(obj3);
        
        for (Sticks i: box1) {
            System.out.println(i);
        }
        
        
    } 
}

class Sticks implements Comparable <Sticks>{
    int size;    
    
    
     public Sticks(int size){
        this.size=size;
    }
    
    
    public int compareTo(Sticks sticks_object){
        if(this.size==sticks_object.size){
            return 0;
        }else if (this.size<sticks_object.size){
            return -1;
        }else {
            return 1;
        }
    }
}

interface Comparable<T>{
    public int compareTo(T o);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sergey, 2019-07-28
@Den4_x

remove your personal interface

// interface Comparable<T> {
// public int compareTo(T o);/
// }

you
want to implement java.lang.Comparable.compare
and add @override annotation to the method
@Override
  public int compareTo(Sticks sticks_object) {

for it to be used
[email protected]
[email protected]
[email protected]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question