How can I use Java's generic types?

Using metadata, Ice applications can customize the Java mapping for Slice sequences and dictionaries.

On this page:

Customizing the Java Mapping for Sequences

The default mapping for a Slice sequence is a native Java array. If an alternative mapping is specified, the type must implement java.util.List<E>, where E is the Java mapping of the element type. For example, here is how we can map a sequence of integers to a linked list:

Slice
["java:type:java.util.LinkedList<Integer>"] sequence<int> IntList;
interface I
{
    IntList getList();
}

When translated by the Slice-to-Java compiler, all occurrences of the IntList type will use java.util.List<Integer> instead of an int array:

Java
IPrx proxy = ...
java.util.List<Integer> list = proxy.getList();
for(int val : list)
{
    System.out.println("entry: " + val);
}

Whenever the generated code must instantiate IntList, it now allocates an instance of java.util.LinkedList<Integer>.

Customizing the Java Mapping for Dictionaries

The default mapping for a Slice dictionary is java.util.Map<K, V> and implemented as java.util.HashMap<K, V>, where K is the Java mapping for the key type and V is the Java mapping for the value type. If an alternative mapping is specified, the type must implement the java.util.Map<K, V> interface. As an example, the following Slice definition changes the default mapping for a dictionary to use a tree map:

Slice
["java:type:java.util.TreeMap<String, Integer>"] dictionary<string, int> StringMap;
interface I
{
    StringMap getMap();
}

We can iterate over the map as shown below:

Java
IPrx proxy = ...
java.util.Map<String, Integer> map = proxy.getMap();
for(String key : map.keySet())
{
    int val = map.get(key);
    System.out.println(key + " = " + val);
}

See Also