2

I want to write a method to find the max value of arraylist. It could be integer or double type.

I believe the below code works for arrays, but not for arraylist?

public static <T extends Comparable<T>> T maxValue(T[] array){       
     T max = array[0];
     for(T data: array){
          if(data.compareTo(max)>0)
              max =data;                
     }
     return max;
}
3
  • "I believe the below code works for arrays, but not for arraylist?" have you tried, with the appropriate modifications (like the first line of the method where you need to use get)? Commented Sep 19, 2020 at 9:14
  • 2
    You would be well-served looking at the source code for Collections.max, given that that method does what you want. Or, use that method, and not reimplement it, of course. Commented Sep 19, 2020 at 9:14
  • This code finds the maximum in an array. Can you share the modifications you made to make it work for an ArrayList and explain where exactly you're stuck? Commented Sep 19, 2020 at 9:17

2 Answers 2

4

First, it should be Comparable<? super T>. Second, the argument needs to be a Collection<T> (or List<T>) instead of an array. Finally, there is the existing Collections.max(Collection<? extends T>) that you can use to implement the method. Like,

public static <T extends Comparable<? super T>> T maxValue(Collection<T> c) {
    return Collections.max(c);
}
Sign up to request clarification or add additional context in comments.

Comments

2
public static void main(String[] args) {
    System.out.println(Collections.max(Arrays.asList(1, 3, 6, 2, 4, 5)));
    System.out.println(Collections.max(Arrays.asList(1.7D, 3.2D, 2.5D, 2.1D, 0.05D, 1.84D)));
}

How about this?

public static void main(String[] args) {
    System.out.println(maxValue(Arrays.asList(1, 3, 6, 2, 4, 5)));
    System.out.println(maxValue(Arrays.asList(1.7D, 3.2D, 2.5D, 2.1D, 0.05D, 1.84D)));
}

public static <T extends Comparable<T>> T maxValue(List<T> array){
    T max = array.get(0);
    for(T data: array){
        if(data.compareTo(max)>0)
            max =data;
    }
    return max;
}

Also, your code works for arraylist if you change parameter type from T[] to List

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.