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
19
votes
1 answer

Why does ArrayList use Object[] (instead of E[]) internally?

ArrayList uses Object array internally: private transient Object[] elementData; and in E get(int) method it's cast to E type. my question is: why ArrayList doesn't use E[] to store objects? I understand that after compiler run, the type-erasure…
Johnny Willer
  • 3,717
  • 3
  • 27
  • 51
19
votes
3 answers

Is it possible to specify both upper and lower bound constraints on type parameters in Java?

Is it possible to specify both upper and lower bound constraints on type parameters in Java? I found a conversation in Sun's forum in which this issue was discussed (apparently before the generics feature was finalized), but there was no final…
Hosam Aly
  • 41,555
  • 36
  • 141
  • 182
19
votes
3 answers

How Can I List a TDictionary in Alphabetical Order by Key in Delphi 2009?

How can I use a TEnumerator to go through my TDictionary in sorted order by key? I've got something like this: var Dic: TDictionary; Enum: TPair; begin Dic := TDictionary.create; …
lkessler
  • 19,819
  • 36
  • 132
  • 203
19
votes
1 answer

Why can't the annotation @SafeVarargs be applied to non-final instance methods?

Why can't the annotation @SafeVarargs be applied to non-final instance methods?
Kumar Abhinav
  • 6,565
  • 2
  • 24
  • 35
19
votes
4 answers

Generic Type Inference with Class Argument

I'm having an issue which defining a generic type based on a type I've passed in. I have a piece of code witch “activates” a class, I can’t get the type information from the type parameter so I am passing in class object (not an instance). However…
Antony Jones
  • 561
  • 1
  • 4
  • 15
19
votes
7 answers

Generics call with Type T in Swift

In my application I want to create an generic method which creates an array of object depening on the given type T. I created the following function: func getArray(key:String) -> T[] { var elements = T[]() for jsonValue in…
Prine
  • 12,192
  • 8
  • 40
  • 59
19
votes
6 answers

Java generics seem to work differently for classes than for methods

I'm following this: http://rickyclarkson.blogspot.com/2006/07/duck-typing-in-java-and-no-reflection.html And I'm trying to adapt this: void doDucklikeThings(T t) { t.quack(); t.walk(); } To this: public class…
candied_orange
  • 7,036
  • 2
  • 28
  • 62
19
votes
1 answer

Java Unchecked Overriding Return Type

I have a project that has the following components: public abstract class BaseThing { public abstract ThingDoer getThingDoer(); } public class SomeThing extends BaseThing { public ThingDoer
Eliezer
  • 7,209
  • 12
  • 56
  • 103
19
votes
2 answers

Why can't I write if (object is HashSet<>) but it's okay if I write (object.GetType() == typeof(HashSet<>))

The title says it all, here's the same with some formatting: Why can't I write public bool IsHashSet(object obj) { return obj is HashSet<>; } but this is okay: public bool IsHashSet(object obj) { return obj.GetType() ==…
Rand Random
  • 7,300
  • 10
  • 40
  • 88
19
votes
4 answers

Can someone explain what does mean and when should it be used and how this construction should cooperate with and ?

I'm using generics rather long time but I've never used construction like List. What does it mean? How to use it? How does it look after erasure? I also wonder: is it something standard in generic programming (template programming?) or…
Roman
  • 64,384
  • 92
  • 238
  • 332
19
votes
8 answers

How can I convert a list of objects to csv?

If I have a list of objects called "Car": public class Car { public string Name; public int Year; public string Model; } How do I convert a list of objects, e.g. List to a csv?
leora
  • 188,729
  • 360
  • 878
  • 1,366
19
votes
5 answers

Getting T.class despite Java's type-erasure

I'm trying to bind an interface to its implementation as read from a configuration file so that I can feed it to my IoC container. Here's roughly what I'm trying to do: public class PropertyImplementationBinder { // ... public Class…
Kaleb Pederson
  • 45,767
  • 19
  • 102
  • 147
19
votes
4 answers

Does F# have generic arithmetic support?

Does F# have the same problem as C# where you can't directly use arithmetic operators with generic T types? Can you write a generic Sum function that would return the sum of any value that supports the arithmetic addition?
Joan Venge
  • 315,713
  • 212
  • 479
  • 689
19
votes
1 answer

Java 8 needs a cast while Java 7 didn't - enum.getClass/getDeclaringClass

I realise Java 8 is still in Beta but this one struck me as odd: public class Fields> { public Fields(Set columns) { // A sample column used to find the universe of the enum of Columns. C sampleCol =…
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213