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
21
votes
3 answers

Convert from Class to TypeReference

Basically just the opposite of this question. I want to convert a Class object to a TypeReference object. I have tried: foo(Class valueType) { TypeReference ref = new TypeReference(){}; } but that just returns a type reference of…
Jason
  • 13,563
  • 15
  • 74
  • 125
21
votes
2 answers

How do I construct a ConstraintViolationException in Bean Validation 1.0?

I am puzzled by the javax.validation API. I am writing a simple test to understand it: Sample sample = new Sample(); Set> violations = validator.validate(sample); if (!violations.isEmpty()) { // Eclipse refuses to let…
Raylite3
  • 837
  • 2
  • 11
  • 22
21
votes
3 answers

Passing Optional.absent() values to methods concisely

One problem with using Guava's Optional type as arguments of methods is that you can't simply write // method declaration public void foo(Optional arg); // compiler error foo(Optional.absent()); due to type inference failing but instead…
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
21
votes
3 answers

Is there any way of imitating OR in Java Generics

EDIT: I changed a bit the example for getting the idea: Like ...without having to create a common interface and make a subclass for Integer and Float to implement it If not, something like this would maybe have more sense…
Whimusical
  • 6,401
  • 11
  • 62
  • 105
21
votes
7 answers

Variable generic return type in C#

Is there any way to have a method return any one of a number of generic types from a method? For example, I have the following: public static T ParseAttributeValue(this XElement element, string attribute) { if(typeof(T) ==…
richzilla
  • 40,440
  • 14
  • 56
  • 86
21
votes
4 answers

What does "out" mean before a Generic type parameter?

I've just saw an unfamiliar syntax while looking for GroupBy return type: public interface IGrouping : IEnumerable MSDN Source I know what does out mean in methods, but not in a generics interface. What does out…
gdoron
  • 147,333
  • 58
  • 291
  • 367
20
votes
3 answers

Creating an array of generic collections

Actually, the question should be Creating an array of generic anything. Why can't the compiler take care of it? The following would be flagged as an error - cannot create generic array. List[] dtoLists = {new ArrayList(),…
Blessed Geek
  • 21,058
  • 23
  • 106
  • 176
20
votes
3 answers

How can I declare a template pointer without knowing the type?

This is what I would like to do: ExampleTemplate* pointer_to_template; cin >> number; switch (number) { case 1: pointer_to_template = new ExampleTemplate(); break; case 2: pointer_to_template = new ExampleTemplate(); …
Nathan
  • 5,322
  • 5
  • 24
  • 24
20
votes
4 answers

How can I refer to the class type a interface is implementing in Java?

I came to a problem with interfaces in a program I'm making. I want to create a interface which have one of its methods receiving/returning a reference to the type of the own object. It was something like: public interface I { ?…
Leonardo Raele
  • 2,400
  • 2
  • 28
  • 32
20
votes
8 answers

Why would I use java.lang.Class.cast

I recently stumbled upon a piece of code that went like this: Object o = .. ; Foo foo = Foo.class.cast(o); I was actually not even aware that java.lang.Class had a cast method, so I looked into the docs, and from what I gather this does simply do a…
Jan Thomä
  • 13,296
  • 6
  • 55
  • 83
20
votes
8 answers

Differences between JVM implementations

Where do JVM Implementations differ (except licensing)? Does every JVM implement Type Erasure for the Generic handling? Where are the differences between: JRockit IBM JVM SUN JVM Open JDK Blackdown Kaffe ..... Deals one of them with…
Martin K.
  • 4,669
  • 7
  • 35
  • 49
20
votes
3 answers

Java generics - is it possible to restrict T to be Serializable?

Is it possible to make something like this? I know that implements cannot be in the <>, but I want to restrict the T to be Serializable somehow. public class Clazz { ... }
user219882
  • 15,274
  • 23
  • 93
  • 138
20
votes
3 answers

Fetching REST resource as List with Jersey

I'm trying to write a generic function in Jersey which can be used to fetch a List of objects of the same type through REST. I based it on the informations found in this forum: link @Override public List fetchResourceAsList(String url) { …
NagyI
  • 5,907
  • 8
  • 55
  • 83
20
votes
9 answers

How do I create a generic class from a string in C#?

I have a Generic class like that : public class Repository {...} And I need to instance that with a string ... Example : string _sample = "TypeRepository"; var _rep = new Repository(); How can I do that? Is that even possible? Thanks!
Paul
  • 12,359
  • 20
  • 64
  • 101
20
votes
3 answers

Generics can't infer second parameter?

I've noticed that the C# compiler doesn't infer second generic parameter. Example: C++ template code: (yea I know that templates don't work like generics) class Test { public: template T test(V v) { //do something with…
Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185