Can you use generics in Apex?

NOTE: This answer is not useful for any code saved in v26.0 or later.

See Winter '13 Release Notes pg. 191 (193 of the PDF)

Take a look at the Parameterized Typing and Interfaces section in the Apex Developer's Guide. This is what you are looking for, I'm pretty sure.

The other way that Generics are commonly used in Apex are what you stated which is in the Collections and Batch Apex classes.

For example, without generics you'd have something like:

List contacts = new List();
contacts.add(new Contact());
contacts.add(new Account());  // uh oh.

With generics you have the compile time type safety:

List<Contact> contacts = new List<Contact>();
contacts.add(new Contact());
contacts.add(new Account()); // won't save/compile because the list knows it only has Contacts.

So, in theory there's some generic code somewhere in the Apex system that handles all of the List work such as:

public class List<T> {
    public void add(T element) { 
      // do the magic
    }
    public T get(Integer index) {
      // do the magic
    }
}

I guess we all need to vote here to make them hear us and allow generics in Apex. This is the only way how generics can appear in Apex. If no ones votes they think we don't really need them.

Tags:

Generics

Apex