Home > Software engineering >  How to write a method with a generic comparable for Java
How to write a method with a generic comparable for Java

Time:04-02

I am trying to write a method to determine the max value of an array. I have designed a test case and solution. The actual does not match the expected.

Expected:

Enter 10 integers: 3 4 12 7 3 4 5 6 4 7
The max number is 12

Actual:

Test1.java:20: error: method max in class Test1 cannot be applied to given types;
        System.out.print("The max number is: ", max(array));
                                                ^
  required: E[]
  found: int[]
  reason: inference variable E has incompatible bounds
    equality constraints: int
    lower bounds: Comparable<E>
  where E is a type-variable:
    E extends Comparable<E> declared in method <E>max(E[])
Test1.java:26: error: incompatible types: int cannot be converted to E
        for(E  i = 1; i < list.length; i  ){
                   ^
  where E is a type-variable:
    E extends Comparable<E> declared in method <E>max(E[])
Test1.java:26: error: bad operand types for binary operator '<'
        for(E  i = 1; i < list.length; i  ){
                        ^
  first type:  E
  second type: int
  where E is a type-variable:
    E extends Comparable<E> declared in method <E>max(E[])
Test1.java:26: error: bad operand type E for unary operator '  '
        for(E  i = 1; i < list.length; i  ){
                                        ^
  where E is a type-variable:
    E extends Comparable<E> declared in method <E>max(E[])
Test1.java:27: error: incompatible types: E cannot be converted to int
            if(list[i].compareTo(max) > 0){
                    ^
  where E is a type-variable:
    E extends Comparable<E> declared in method <E>max(E[])
Test1.java:28: error: incompatible types: E cannot be converted to int
                max = list[i];
                           ^
  where E is a type-variable:
    E extends Comparable<E> declared in method <E>max(E[])
6 errors

Attempt

package Generics;
import java.util.ArrayList;
import java.util.Scanner;

/*
    name: Evan Getis
    date: 04/01
    program: max integer
*/
public class Test1 {
    
    public static void main(String args[]){
        int[] array = new int[10];
        Scanner input = new Scanner(System.in);
        for(int i = 0; i <= 10; i  ){
            System.out.print("Enter 10 integers: ");
            int integer    = input.nextInt();
            array[i] = integer;
        }
        System.out.print("The max number is: ", max(array));
    }

    public static <E extends Comparable <E>> E max(E[] list){
        E max = list[0];
    
        for(E  i = 1; i < list.length; i  ){
            if(list[i].compareTo(max) > 0){
                max = list[i];
            }
        }

        return max;
    }
}

Any help with this would be greatly appreciated

CodePudding user response:

import java.util.ArrayList; import java.util.Scanner;

public class Test1 {

public static void main(String args[]){
    Integer[] array = new Integer[10];
    Scanner input = new Scanner(System.in);
    System.out.print("Enter 10 integers: ");
    for(int i = 0; i < 10; i  ){
        int integer    = input.nextInt();
        array[i] = integer;
    }
    System.out.print("The max number is:" max(array));
}

public static <E extends Comparable <E>> E max(E[] list){
    E max = list[0];

    for(int i = 1; i < list.length; i  ){
        if(list[i].compareTo(max) > 0){
            max = list[i];
        }
    }

    return max;
}

}

CodePudding user response:

issue first is int[] inside main need to be replace with Integer[] because auto boxing / unboxing works on int to Integer or Integer. it does not work for arrays.

Integer[] is needed because of generics work with classes or interface not with primitive type

second issue is with for loop to find max u need to use int not E type

and as JDK 8 is very old now i hope you must be familiar with streams using which you can write single line readable code


  public static void main(String[] args) {
        Integer[] arr = new Integer[]{2,4,5,6,3,24,5};
        System.out.print(getMax(arr));
    }

    public static <E extends Comparable<E>> E getMax(E[] arr) {
        return Arrays.stream(arr).max((a,b)->a.compareTo(b)).orElseThrow();
    }

max function except comparator interface so i converted it for Comparable

  public static void main(String[] args) {
        Integer[] arr = new Integer[]{2,4,5,6,3,24,5};
        System.out.print(getMax(arr,Integer::compare));
    }

    public static <E> E getMax(E[] arr,Comparator<E> comparator) {
        return Arrays.stream(arr).max(comparator).orElseThrow();
    }

here you can change whole logic while function calling.

CodePudding user response:

You are specifying that you are passing in an array of Comparable objects in <E extends Comparable<E>>, but you are passing in a primitive array of int, and int does not implement Comparable. You need to use an object type that implements Comparable, such as Integer.

  •  Tags:  
  • java
  • Related