Kurt16
Kurt16

Reputation: 35

How to find out the lowest value with a generic method?

I am trying to resolve an excercise about finding out the lowest value in array using loop. The excercise is about generics. But i have a hard to find out the solution. For an array of string i will use " if (minimum.compareTo(list[i]) > 0) ". I am stuck in how to do this with an array of integer. Any hint or help is very appreciate.

There is my code:

 public class Excercise {

        public static void main(String[] args) {
            //Create an array 
            Integer[] intArray = { new Integer(45), new Integer(2), new Integer(6), new Integer(15) };
            //print the lowest value
            System.out.print(min(intArray));
            // min(intArray);
        }

        public static <E extends Comparable<E>> E min(E[] list) {
            E minValue = list[0];
            for(int i = 1; i < list.length; i++) {
            if(minValue.compareTo(list[i]) {    <-- i get an error her
                minValue = list[i];


         return minValue;
   }
}

Upvotes: 0

Views: 6176

Answers (3)

AKHIL K
AKHIL K

Reputation: 94

because compareTo() method will return integer value change

if(minValue.compareTo(list[i]) { 

to

if(minValue.compareTo(list[i]) > 0) { 

Upvotes: 2

Joeri Hendrickx
Joeri Hendrickx

Reputation: 17435

compareTo doesn't return a boolean, so you can't use it as a condition of your if clause.

See http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html#compareTo%28T%29

Instead, it an returns int. If the result is above zero, that means the first term is greater. If it is below, it is lesser.

So use if(minValue.compareTo(list[i])>0)) instead.

There are other bugs in the code (mostly typos). I will leave those to you.

Upvotes: 2

Pablo Lozano
Pablo Lozano

Reputation: 10342

The proper method should be as follows:

public static <E extends Comparable<E>> E min(E[] list) {
     E minValue = list[0];
     for(int i = 1; i < list.length; i++) {
         if( minValue.compareTo(list[i]) > 0) { //compareTo always returns an int
             minValue = list[i];
         }
     }
     return minValue; // returs the minimum after checking all the array
}

Upvotes: 1

Related Questions