Questions tagged [generics]

Generics are a form of parametric polymorphism found in a range of languages, including .NET languages, Java, Swift, Rust and Go (since 1.18).

is a language feature found in certain languages to enable a form of . They typically allow the programmer to express concepts such as "A list of some type T" in a type-safe manner. Prior to the addition of generics to the language and the , programmers using these languages were forced to downcast from the base Object when using some general purpose classes, such as collection classes.

With the addition of , the programmer can instead use types such as List<int> to create type-safe lists which only store int objects.

In-depth detail for examples and concepts specifically for C# Generics is provided by Microsoft here. Information on Java generics can be found here.

Unlike , generics are typically limited to simple type substitution, without the ability of templates to specialize in specific types (infamously misused in the C++ standard library in std::vector<bool> which behaves radically different from any other std::vector<T>). This also means that generics are not well suited for , which typically relies on an ability to tailor generic algorithms for specific parameter types (again using a C++ example, pointers are usable with any generic algorithm expecting arguments to be iterators).

Java Generics Tutorials

  1. Java Generic methods and generic classes Tutorials
  2. Java Generics FAQs

.NET Generics Tutorials

  1. Introduction to Generics
  2. C# Generics

Rust Generics Tutorials

  1. Generics chapter from The Rust Book
  2. Generics section from Rust By Example

Go Generics Tutorials

  1. Tutorial: Getting started with generics

Example

C# without Generics

var list = new System.Collections.ArrayList();
list.Add(1);
list.Add("banana"); // will compile

int n = (int) list[0];
int s = (int) list[1]; // will compile, but throws an InvalidCastException

C# with Generics

var list = new System.Collections.Generic.List<int>();
list.Add(1);
//list.Add("banana"); -- Will not compile

int n = list[0];
//string s = list[1]; -- will not compile
49056 questions
179
votes
4 answers

What is reification?

I know that Java implements parametric polymorphism (Generics) with erasure. I understand what erasure is. I know that C# implements parametric polymorphism with reification. I know that can make you write public void dosomething(List input)…
Martijn
  • 11,964
  • 12
  • 50
  • 96
179
votes
8 answers

Java Enum definition

I thought I understood Java generics pretty well, but then I came across the following in java.lang.Enum: class Enum> Could someone explain how to interpret this type parameter? Bonus points for providing other examples of where a…
Dónal
  • 185,044
  • 174
  • 569
  • 824
179
votes
9 answers

How to make a Java class that implements one interface with two generic types?

I have a generic interface public interface Consumer { public void consume(E e); } I have a class that consumes two types of objects, so I would like to do something like: public class TwoTypesConsumer implements Consumer,…
daphshez
  • 9,272
  • 11
  • 47
  • 65
178
votes
14 answers

How do I clone a generic List in Java?

I have an ArrayList that I'd like to return a copy of. ArrayList has a clone method which has the following signature: public Object clone() After I call this method, how do I cast the returned Object back to ArrayList?
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
177
votes
3 answers

Cast Object to Generic Type for returning

Is there a way to cast an object to return value of a method? I tried this way but it gave a compile time exception in "instanceof" part: public static T convertInstanceOfObject(Object o) { if (o instanceof T) { return (T) o; }…
sedran
  • 3,498
  • 3
  • 23
  • 39
175
votes
16 answers

How to initialize a List to a given size (as opposed to capacity)?

.NET offers a generic list container whose performance is almost identical (see Performance of Arrays vs. Lists question). However they are quite different in initialization. Arrays are very easy to initialize with a default value, and by…
Boaz
  • 25,331
  • 21
  • 69
  • 77
175
votes
13 answers

What are the differences between "generic" types in C++ and Java?

Java has generics and C++ provides a very strong programming model with templates. So then, what is the difference between C++ and Java generics?
popopome
  • 12,250
  • 15
  • 44
  • 36
174
votes
8 answers

Why shouldn't Java enum literals be able to have generic type parameters?

Java enums are great. So are generics. Of course we all know the limitations of the latter because of type erasure. But there is one thing I don't understand, Why can't I create an enum like this: public enum MyEnum { LITERAL1, …
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
173
votes
2 answers

Generic return type upper bound - interface vs. class - surprisingly valid code

This is a real-world example from a 3rd party library API, but simplified. Compiled with Oracle JDK 8u72 Consider these two methods: X getCharSequence() { return (X) "hello"; } X getString() { …
Adam Michalik
  • 9,678
  • 13
  • 71
  • 102
173
votes
6 answers

How do I get the type name of a generic type argument?

If I have a method signature like public string myMethod( ... ) How can I, inside the method, get the name of the type that was given as type argument? I'd like to do something similar to typeof(T).FullName, but that actually works...
Tomas Aschan
  • 58,548
  • 56
  • 243
  • 402
172
votes
18 answers

Get type of a generic parameter in Java with reflection

Is it possible to get the type of a generic parameter? An example: public final class Voodoo { public static void chill(List aListWithTypeSpiderMan) { // Here I'd like to get the Class-Object 'SpiderMan' Class typeOfTheList =…
cimnine
  • 3,987
  • 4
  • 33
  • 49
169
votes
7 answers

How to pass a class type as a function parameter

I have a generic function that calls a web service and serialize the JSON response back to an object. class func invokeService(service: String, withParams params: Dictionary, returningClass: AnyClass, completionHandler handler:…
Jean-Francois Gagnon
  • 3,141
  • 4
  • 20
  • 27
169
votes
9 answers

Java: Instanceof and Generics

Before I look through my generic data structure for a value's index, I'd like to see if it is even an instance of the type this has been parametrized to. But Eclipse complains when I do this: @Override public int indexOf(Object arg0) { if…
Nick Heiner
  • 119,074
  • 188
  • 476
  • 699
168
votes
10 answers

Instantiating a generic class in Java

I know Java's generics are somewhat inferior to .Net's. I have a generic class Foo, and I really need to instantiate a T in Foo using a parameter-less constructor. How can one work around Java's limitation?
ripper234
  • 222,824
  • 274
  • 634
  • 905
167
votes
7 answers

How do I implement IEnumerable

I know how to implement the non generic IEnumerable, like this: using System; using System.Collections; namespace ConsoleApplication33 { class Program { static void Main(string[] args) { MyObjects myObjects = new…
JMK
  • 27,273
  • 52
  • 163
  • 280