user2999509
user2999509

Reputation: 107

How to compare two ints in a list?

I take in a list of integers using a scanner. Put them in a list, and then implement my own sorter to sort them from smallest to biggest. In the main file when using the code to sort

Sorting.selectionSort(intList);

The error i got is

"The method selectionSort(Comparable[]) in the type Sorting is not applicable for the arguments (int[])

 public static void selectionSort (Comparable[] list)
   {
      int min;
      Comparable temp;

      for (int index = 0; index < list.length-1; index++)
      {
         min = index;
         for (int scan = index+1; scan < list.length; scan++)
            if (list[scan].compareTo(list[min]) < 0)
               min = scan;
         // Swap the values
         temp = list[min];
         list[min] = list[index];
         list[index] = temp;
      }
   }

if i were to use

if (intList[scan].compareTo(intList[min]) < 0)

The error i will get is:

is "Cannot invoke compareTo on primitive type of int"

Upvotes: 0

Views: 135

Answers (4)

kar
kar

Reputation: 3651

Just pondering why you wouldn't want to use the == operator since you just want to compare 2 int.

For example:

int intCompare(){
            int[] intArray = {1, 10, 2, 3, 4, 5, 10, 6, 7, 8, 9};
            for(int x=0; x < intArray.length-1; x++){
                if(intArray[x] == intArray[x+1]){
                    return intArray[x];
                }
            }
            return -1;
        }

Upvotes: 0

Karibasappa G C
Karibasappa G C

Reputation: 2732

Basically for any collection if we consider, we cant add any primitive. whatever we want to add to collection , it must be of Object type. so even if you have added a int to list implicitly primitive int is autoboxed to Integer wrapper object. so i think the method you defined is wrong with the parameter as comparable[], it should receive only List.

so check this. and if you share the code of your input construction into a list then we can easily answer this

Upvotes: 0

Keerthivasan
Keerthivasan

Reputation: 12880

Use Integer instead of int. Primitives are not allowed in the Collections. Please take a look at Wrapper classes in Java. In Java, there is a Wrapper class available for every primitives. Collections need references to Objects, they cannot contain real primitives. Example : Integer is the Wrapper class for int primitive

Upvotes: 0

ylun
ylun

Reputation: 2534

You cannot compare any primitives by calling a method, in this case the .compareTo method.

The error that you get is exactly what is means, you must instead use the object wrapper, Integer, if you want to compare them using a method. Cheers.

Upvotes: 1

Related Questions