timothya
timothya

Reputation: 47

Generic Type Repeated

I have this class...

public abstract class LoadboardTable
{
    protected Map<String, HashMap<HasTableFields, String>>  table   = new TreeMap<String, HashMap<HasTableFields, String>>();

    public Set<Entry<String, HashMap<HasTableFields, String>>> getEntries()
    {
        return table.entrySet();
    }

    ...
}

In other classes, I am constantly repeating the generic type. For example...

for (Entry<String, HashMap<HasTableFields, String>> entry : myTable.getEntries()){}

Set<Entry<String, HashMap<HasTableFields, String>>> entries = otherTable.getEntries();

etc, etc...

This generic type is repeated and littered all over the application. Is there a better way? If I ever decide to change the generic type of the table Map object in the LoadboardTable class, I'll be changing it everywhere else too for days. Plus it's just a huge pain to keep typing it.

Upvotes: 0

Views: 182

Answers (3)

RussColwell
RussColwell

Reputation: 61

public abstract class LoadboardTable<T,O>
{
    protected Map<T, HashMap<O, T>>  table   = new TreeMap<T, HashMap<O, T>>();

    public Set<Entry<T, HashMap<O, T>>> getEntries()
    {
        return table.entrySet();
    }
}

Upvotes: 0

David
David

Reputation: 43

3 Advises:

  1. Instead of using so much generics, think about classes that you actually want to implement, instead of solving everything with generics.
  2. Use the diamond operator with Java 7.
  3. When using eclipse you can write just "getEntries" and then press CTRL+1 and click "assign to local variable" - this will automatically create a local variable with the right type. This does not solve the problem, but will make it a bit faster to write.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692081

There is no way to avoid the repetition, except in the constructor, since Java 7:

protected Map<String, HashMap<HasTableFields, String>> table = new TreeMap<>();

You would have better code, and less to type, if you encapsulated the HashMap and entries in well-defined classes, though. It looks like you're using objects as open data structures, instead of using them as closed objects offering behaviour and keeping their state encapsulated.

Upvotes: 3

Related Questions