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
20
votes
2 answers

Java interface extends Comparable

I want to have an interface A parameterised by T A, and also want every class that implements it to also implement Comparable (with T and its subtypes). It would seem natural to write interface A extends Comparable, but that…
oceola
  • 241
  • 1
  • 2
  • 4
20
votes
2 answers

Java 8 and Generalized Target-Type Inference

I have installed the last JDK 8 ea b114 to test the new language features. However the inference in chained calls seems not to work yet. If I write: Iterator it = new ArrayList<>().iterator(); the compiler give me an error. However…
xdevel2000
  • 20,780
  • 41
  • 129
  • 196
20
votes
1 answer

How to compare object's type with a generics type, irrelevant to generic argument?

Best way to illustrate my question is with this example code: class Item {} class Container< T > {} class Program { static void DoSomething( object something ) { if( typeof( Item ) == something.GetType() ) { …
grigoryvp
  • 40,413
  • 64
  • 174
  • 277
20
votes
4 answers

How to create a Java class, similar to a C++ template class?

How do I write an equivalent of this in Java? // C++ Code template< class T > class SomeClass { private: T data; public: SomeClass() { } void set(T data_) { data = data_; } };
sivabudh
  • 31,807
  • 63
  • 162
  • 228
20
votes
5 answers

C#: Generic types that have a constructor?

I have the following C# test code: class MyItem { MyItem( int a ) {} } class MyContainer< T > where T : MyItem, new() { public void CreateItem() { T oItem = new T( 10 ); } } Visual Studio can't compile it, the…
grigoryvp
  • 40,413
  • 64
  • 174
  • 277
20
votes
13 answers

The type Collection is not generic; it cannot be parameterized with arguments

I have a strange problem with Eclipse Galileo. I set Java 1.6 as my JRE. On this line of code List templates = new ArrayList (); I see the following error in Eclipse's problem list: The type Collection is not generic; it cannot be parameterized…
dbf
  • 415
  • 2
  • 10
  • 18
20
votes
5 answers

Creating generic array in Java via unchecked type-cast

If I have a generic class Foo, I am not allowed to create an array as follows: Bar[] bars = new Bar[]; (This will cause the error "Cannot create a generic array of Bar"). But, as suggested by dimo414 in an answer to this question (Java how to:…
Markus A.
  • 12,349
  • 8
  • 52
  • 116
20
votes
2 answers

Can Java infer type arguments from type parameter bounds?

The following test program is derived from a more complicated program that does something useful. It compiles successfully with the Eclipse compiler. import java.util.ArrayList; import java.util.List; public class InferenceTest { public static…
Trevor Robinson
  • 15,694
  • 5
  • 73
  • 72
20
votes
7 answers

C# generics problem - newing up the generic type with parameters in the constructor

I am trying to create a generic class which new's up an instance of the generic type. As follows: public class HomepageCarousel : List where T: IHomepageCarouselItem, new() { private List GetInitialCarouselData() { …
ChrisCa
  • 10,876
  • 22
  • 81
  • 118
20
votes
5 answers

Java: Parameterized Runnable

Standard Runnable interface has only non-parametrized run() method. There is also Callable interface with call() method returning result of generic type. I need to pass generic parameter, something like this: interface MyRunnable { public…
mschayna
  • 1,300
  • 2
  • 16
  • 32
20
votes
9 answers

Overriding "equals" method: how to figure out the type of the parameter?

I'm trying to override equals method for a parameterized class. @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Tuple)) return…
Nick Heiner
  • 119,074
  • 188
  • 476
  • 699
20
votes
4 answers

"where" keyword in class declaration in c sharp

Could anyone help me with the line where TEntity : class, IEntity, new() in the following class declaration. public abstract class BaseEntityManager where TEntity : class, IEntity, new()
user193442
  • 213
  • 1
  • 2
  • 4
20
votes
6 answers

What makes a template different from a generic?

I understand the aspects of templates in C++ that are different from generics in Java and C#. C# is a reification, Java uses type erasure, C++ uses duck typing, etc. There are a number of things C++ templates can do that Java and C# generics can't…
Eva
  • 4,397
  • 5
  • 43
  • 65
20
votes
3 answers

Advanced polymorphism in Java

I have classes in advanced programming at my university and I have a little trouble understanding how this code works. public final class GenericClass { private void overloadedMethod(Collection o) { …
20
votes
5 answers

Converting non-generic List type to Generic List type in Java 1.5

I have a List that is guaranteed to contain just one type object. This is created by some underlying code in a library that I cannot update. I want to create a List based on the incoming List object so that my calling code is talking…
Shaun
  • 4,057
  • 7
  • 38
  • 48