Tutorial details

[TUT] Easier / Quicker Generic Collection Creation | App Code for Sale | Preview

[TUT] Easier / Quicker Generic Collection Creation | Android Tutorial

Quick and easy way to create a collection of objects

Overview PAGE TOP

Sick of repeating your generics declaration?Sick of repeating your generics declaration?

1   List<SomeObject> listOfSomething = new ArrayList<SomeObject>();
2   Map<SomeKey, SomeObject> mapOfSomething = new HashMap<SomeKey, SomeObject>();

For a quick and easy way to create a collection of objects you can do the below.

Create yourself a util class:

1   package com.blundell.util;
3   import java.util.ArrayList;
4   import java.util.HashMap;
6   public class Collections {
8       public static <E> ArrayList<E> newArrayList() {
9           return new ArrayList<E>();
10      }
12      public static <K, V> HashMap<K, V> newHashMap() {
13          return new HashMap<K, V>();
14      }
16  }

Then each time you only need to declare your generics once.

1   List<SomeObject> listOfSomething = Collections.newArrayList();
2   Map<SomeKey, SomeObject> mapOfSomething = Collections.newHashMap();

This is due to Type Inference. Inspired by Joshua Bloch’s – Effective Java (second edition)


Reference PAGE TOP


0 Comments Leave a comment

Please login in order to leave a comment.

Newest first

to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.