Calculate range of ArrayList Write a method range that accepts an ArrayList of integers as a parameter and that returns the range of values contained in the list, which is defined as 1 more than the difference between the largest and smallest elements.


I feel like I'm beginning to understand conditionals, but for some reason this just makes me cringe. Is it good practice to have these conditionals as catch-alls in the beginning? Should I be using else ifs instead?

public static int range(ArrayList&lt;Integer&gt; list){
    if(list.size() == 0){
        return 0;
    }
    if(list.size() == 1){
        return 1;
    }

    int firstElement = list.get(1);
    int max = firstElement;
    int min = firstElement;

    for(int i = 0; i &lt; list.size(); i++){
        int elementValue = list.get(i);
        if(max &lt; elementValue){
            max = elementValue;
        }
        if(elementValue &lt; min){
        min = elementValue;
        }
    }
return (max - min) + 1;
}
Use this:

if (list.size() &lt;= 1) {
    return list.size();
}




list.get(1) refers to the second element in the list, not the first. Either rename the variable or use list.get(0). With that change, you don't need to use a list size of 1 as a special case.



Only being able to do the job on ArrayList is quite useless. Your method can take an argument of type List instead.



No, it is no need to use else if in this case.

Rewriting with Iterable

You currently check the first item in the list twice. If your code would accept an Iterable&lt;Integer&gt;, you would support even more data types (You still support ArrayList also).

The only thing you need is the Iterator from the iterable. When you have that, you can first see if it contains at least one item. If it doesn't, return 0. Otherwise, you do similar to what you are already doing, but with different code.

public static int range(Iterable&lt;Integer&gt; numbers) {
    Iterator&lt;Integer&gt; iterator = numbers.iterator();
    if (!iterator.hasNext()) {
        return 0;
    }

    int firstElement = iterator.next();
    int max = firstElement;
    int min = firstElement;
    while (iterator.hasNext()) {
        int elementValue = iterator.next(i);
        if (max &lt; elementValue) {
            max = elementValue;
        }
        if (elementValue &lt; min) {
            min = elementValue;
        }
    }
    return (max - min) + 1;
}


Happy coding!