13.3. Consuming Generic Types

The J# syntax for consuming generic types is very similar to the generics syntax that is used with C#. This section takes a quick look at a few simple generic declarations to provide you with a better feel for the basic syntax of consuming generics with J#:

[J# code]
import System.Collections.ObjectModel.*;
import System.Collections.Generic.*;

public void TestTypeConstruction(Object param1) {
    Collection<int> intList = new Collection<int>();
    intList.Add(123);

    Dictionary<String, Integer> aDict = new Dictionary<String, Integer>();
    aDict.Add("Key", new Integer(123));

    ICollection<String> strCollection = new Collection<String>();
    strCollection.Add("Test");

    if (param1 instanceof ICollection<String>)
System.out.println("Instance matched");

    IEnumerable<String> strEnum = (IEnumerable<String>)strCollection;
}

This example uses some of the generic types that are supplied by the System.Collection.Generic namespace. If you've looked at C# generics at all, you may be doing a double take as you look at this code. The syntax in this example is actually identical to the C# generics syntax. You'll notice that J# uses the angle brackets to enclose the list of type arguments that are supplied when constructing a generic type. As you construct each type in this example, you'll also notice that the default, parameterless constructor is used, which is represented by the closed parentheses at the end of each declaration.

Constructed generic types behave like any other J# ...

Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.