paolo@bimodesign.com | +34 608 61 64 10

Java

        

Java - Array, List y Map

This is the first post about Java and I'm going to show the difference between HashMap and ArrayList.
The objective is to figure out this code

public static <I> ConditionBase<?, I> NewInstance(I fieldIndexer, int operationId, int paramsTypeId, String paramsList)


List
We start explaining the meaning of ArrayList that starting of the version 1.5 of Java is possible to define the type of a list, in this way

List<String> lista = new ArrayList<String>();

and starting of 1.7 in this way

List<String> lista = new ArrayList<>();

In that way we define a list of "string" and only of that type of data. So

lista.add("string value");
lista.add(123);  // compile error
lista.add(true); // compile error

If we need to define a generic list, we'll define in that way.

List<Object> lista = new ArrayList<>();

But that is not a good pratice because we cannot protect by the "side effects".

Map
A map accept two parameters (or called generics), key and value, in that way for example

Map<String, Boolean> map = new HashMap<>();

and to add a value the code will be

map.put("hello", true);

The number or generic is variable and usually are two.
The generics allow the wildcard values two, using the caracter "?". It's possible to apply it both list and maps, in this way

List<?> lista = getValues();
 for (Object o : lista) {
         System.out.println(o == null ? "" : o.toString());
 }

But the list could be accessed and not modified. So this code will return compiling error

 lista.add("pippo");

For more information about the Generics, see this link.

To read and write a list we define the method as Collection.

 void readStudents(Collection<? extends Student> coll){...}
 readStudents(Arrays.asList(
         new Student("Paolo"),
         new Student("Manolo"));

To produce a list

void writeStudent(Collection<? super Student> coll){...}

List<? super Student> persons = new ArrayList<Person>();
writeStudent(persons);

The clases can define the generics:

class MyMap<K,V> extends HashMap<K,V> {...}

and can define the methods

<T> List<T> merge(List<T> a, List<T> b);

It's possible to define a limitation, for example:

<T extends Number> T sum(T a, T b);

So, to came back at the first code example:

public static <I> ConditionBase<?, I> NewInstance(I fieldIndexer, int operationId, int paramsTypeId, String paramsList)

We have a generic method to <I> that return a element ConditionBase<?, I> (a class defined to I and to element that we can use and then we define as "?"