0

I want to be able to calculate the largest value in a list of numbers

I want the type of number to be any number (it should work with double, int, long, etc)

The method that I tried to create for this is not working and keeps returning the first value of the array

public static <V extends Number & Comparable<V>> V max(final V... numbers) { V currentLargest = numbers[0]; for (V value : numbers) { int arraySize = 0; if (currentLargest.compareTo(numbers[arraySize]) < 0) { currentLargest = numbers[arraySize]; } arraySize = arraySize + 1; } return currentLargest; } 

I dont know what I am doing wrong

1 Answer 1

2

Okay, there are a few issues with the code you have written. First off, I would recommend putting in a check to make sure the numbers array is not null. While this is not required, I would still recommend it. However, the most significant issue you are having is how you are attempting to compare your currentLargest value to a value on the array. You are always comparing against the first value of the array every single time as you have your arraySize variable updated to zero with every iteration of your loop.

I created a method that does exactly what you are asking with the bugs from your method fixed. I hope this helps.

 public static <V extends Comparable<? super V>> V max(final V... numbers) { if (numbers == null || numbers.length == 0) { return null; } V currentLargest = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (currentLargest.compareTo(numbers[i]) < 0) { currentLargest = numbers[i]; } } return currentLargest; } 
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent. I wrote almost the same answer (since deleted). Small tweak, why not make it <V extends Comparable<? super V>> then it's generic to any Comparable<V>.
@ElliottFrisch That is a really good suggestion. I will go ahead and change my answer to reflect that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.