Bill Farmer

Random thoughts on random subjects

Java Collections

by Bill Farmer. Categories: Hacking .

I find Java Collections frustrating and insane. I have been through this loop on several occasions. I decide I want a list to do whatever. So I look up List in the docs and find it’s an interface, ie: roll yer own. So I look down the hierarchy and find AbstractList, which is abstract, again: roll yer own. So finally I get to ArrayList which might do the job, but the docs aren’t too clear, so I try it and it works. I just want a list that will do the job. I don’t care what it stores the data in, that level of detail is supposed to be obscured and possibly subject to change anyway.

So why can’t a List be a list that you can actually do something useful with? I don’t get this sort of nonsense with other languages. An AbstractList is fine, it is what it is. It can’t be that difficult to dream up a suitable name for a list like interface that isn’t just List.

Update

Having written several android apps utilising java Collections objects, one way to deal with this issue is to declare all variables as an interface – List, Map, or Set, both when initially declared and in function parameters, etc, and use the particular implementation you want when you create a new one. I haven’t found this suggestion in the docs anywhere.

    private List<String> list;
    private Map<String, Integer> map;
    private Set<String> set;

    // onCreate
    @Override
    public void onCreate()
    {
        list = new ArrayList<String>();
        map = new LinkedHashMap<String, Integer>();
        set = new ArraySet<String>();
        // ...
    }

    // Get map
    public Map<String, Integer> getMap()
    {
        return map;
    }


See Also