Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass integer array to comparable in java

public class Stack {

    public static void main(String[] args) {
        // Strings[]
        // names={"news","ask","man","querty","lang","love","poppye","zebra","hello"};
        int[] names = { 31, 5343, 8776, 90, 123, 33 };// shows me an error
        Selection sec = new Selection();
        sec.sort(names);
        for (int i = 0; i < names.length; i++) {
            System.out.println(names[i]);
        }
    }
}

class Selection {
    int valNow;

    public void sort(Comparable[] names) {
        for (int i = 0; i < names.length; i++) {
            boolean swapOn = false;
            int min = -200;
            int pointer = 0;

            for (int j = i + 1; j < names.length; j++) {

                if (less(names[i], names[j])) {
                    if (valNow > min) {
                        min = valNow;
                        pointer = j;
                        System.out.println("Pointer:" + pointer + " "
                                + "Highest:" + min);
                        swapOn = true;
                    }
                }
            }
            if (swapOn) {
                swap(names, i, pointer);
            }
        }

    }

    public void swap(Comparable[] name, int x, int y) {
        System.out.println("Gonna swap:" + name[x] + " and " + name[y]);
        Comparable inter = name[x];
        name[x] = name[y];
        name[y] = inter;

    }

    public boolean less(Comparable one, Comparable two) {
        boolean send = false;

        valNow = one.compareTo(two);
        System.out.println(valNow);
        if (valNow > 0) {
            send = true;
        } else if (valNow == 0) {
            send = true;
        }

        return send;
    }
}

I am able to pass and sort String array to Comparable[] in selection class sort() method but passing int array to sort() shows me error that Comparable[] is not applicable to int[]!!I need to sort all types of data with same code! Please help me out!

like image 471
karthick prasad Avatar asked Dec 06 '25 17:12

karthick prasad


1 Answers

Use Integer instead of int. int is not a class and have no compareTo method.

like image 149
Paco Abato Avatar answered Dec 08 '25 06:12

Paco Abato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!