java is smart – using var

I was working on some code and seeing how many local variables I could substitute with var. I was a little surprised to learn that the below compiles. It makes sense to me that mags is good because the type is there. It’s cool that years and sorted can infer the type of Integer as well.

package lists;

import java.util.*;

public class Magazines {

    public static void main(String[] args) {
        var mags = new HashMap<String, Integer>();
        mags.put("People", 1974);
        mags.put("Readers Digest", 1922);
        mags.put("The Economist", 1843);

        var years = mags.values();

        var sorted = new ArrayList<>(years);
        Collections.sort(sorted);

        int first = sorted.get(0);
        System.out.println(first);
    }
}

2 thoughts on “java is smart – using var

  1. Hi Jeanne, thanks for sharing.
    The L21 throws a IndexOutOfBoundsException, I think need to be `sorted.size()-1` instead.

  2. Removed that line from the example. What I was trying to do here was write a mock exam question that checked if the reader caught the size() – 1 thing. It’s not the point of the post though so I should have removed it here!

Leave a Reply

Your email address will not be published.