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).

Filter by
Sorted by
Tagged with
1638 votes
24 answers
1.8m views

How to Sort a List<T> by a property in the object

I have a class called Order which has properties such as OrderId, OrderDate, Quantity, and Total. I have a list of this Order class: List<Order> objListOrder = new List<Order>(); ...
Shyju's user avatar
  • 217k
1438 votes
22 answers
503k views

Create Generic method constraining T to an Enum

I'm building a function to extend the Enum.Parse concept that Allows a default value to be parsed in case that an Enum value is not found Is case insensitive So I wrote the following: public static ...
johnc's user avatar
  • 39.9k
1295 votes
9 answers
362k views

How do I call a generic method using a Type variable?

What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime? Consider the following sample code - inside the ...
Bevan's user avatar
  • 44k
1242 votes
32 answers
1.0m views

How can I create a generic array in Java?

Due to the implementation of Java generics, you can't have code like this: public class GenSet<E> { private E a[]; public GenSet() { a = new E[INITIAL_ARRAY_LENGTH]; // Error: ...
tatsuhirosatou's user avatar
1052 votes
13 answers
362k views

Difference between <? super T> and <? extends T> in Java [duplicate]

What is the difference between List<? super T> and List<? extends T> ? I used to use List<? extends T>, but it does not allow me to add elements to it list.add(e), whereas the List&...
Anand's user avatar
  • 12.1k
908 votes
17 answers
169k views

What is PECS (Producer Extends Consumer Super)?

I came across PECS (short for Producer extends and Consumer super) while reading up on generics. Can someone explain to me how to use PECS to resolve confusion between extends and super?
peakit's user avatar
  • 29k
908 votes
19 answers
140k views

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

I'm a bit confused about how Java generics handle inheritance / polymorphism. Assume the following hierarchy - Animal (Parent) Dog - Cat (Children) So suppose I have a method doSomething(List<...
froadie's user avatar
  • 81.5k
905 votes
25 answers
999k views

How do I get a class instance of generic type T?

I have a generics class, Foo<T>. In a method of Foo, I want to get the class instance of type T, but I just can't call T.class. What is the preferred way to get around it using T.class?
robinmag's user avatar
  • 17.9k
850 votes
18 answers
879k views

How to get the type of T from a member of a generic class or method

Let's say I have a generic member in a class or method, like so: public class Foo<T> { public List<T> Bar { get; set; } public void Baz() { // get type of T } ...
Patrick Desjardins's user avatar
820 votes
15 answers
362k views

What is a raw type and why shouldn't we use it?

Questions: What are raw types in Java, and why do I often hear that they shouldn't be used in new code? What is the alternative if we can't use raw types, and how is it better?
polygenelubricants's user avatar
758 votes
30 answers
905k views

How do I clone a generic list in C#?

I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn't seem to be an option to do list.Clone(). Is there an easy way around ...
Fiona's user avatar
  • 7,887
704 votes
19 answers
928k views

How do I make the method return type generic?

Consider this example (typical in OOP books): I have an Animal class, where each Animal can have many friends. And subclasses like Dog, Duck, Mouse etc which add specific behavior like bark(), ...
Sathish's user avatar
  • 20.9k
704 votes
22 answers
541k views

How do I address unchecked cast warnings?

Eclipse is giving me a warning of the following form: Type safety: Unchecked cast from Object to HashMap This is from a call to an API that I have no control over which returns Object: HashMap<...
skiphoppy's user avatar
  • 100k
669 votes
30 answers
862k views

Get generic type of class at runtime

How can I achieve this? public class GenericClass<T> { public Type getMyType() { //How do I return the type of T? } } Everything I have tried so far always returns type ...
Glenn's user avatar
  • 6,715
665 votes
13 answers
249k views

How can I return NULL from a generic method in C#?

I have a generic method with this (dummy) code (yes I'm aware IList has predicates, but my code is not using IList but some other collection, anyway this is irrelevant for the question...) static ...
656 votes
29 answers
612k views

Create instance of generic type in Java?

Is it possible to create an instance of a generic type in Java? I'm thinking based on what I've seen that the answer is no (due to type erasure), but I'd be interested if anyone can see something I'm ...
David Citron's user avatar
  • 43.4k
638 votes
32 answers
852k views

Remove duplicates from a List<T> in C#

Anyone have a quick method for de-duplicating a generic List in C#?
JC Grubbs's user avatar
  • 39.8k
612 votes
28 answers
564k views

How to remove elements from a generic list while iterating over it?

I am looking for a better pattern for working with a list of elements which each need processed and then depending on the outcome are removed from the list. You can't use .Remove(element) inside a ...
InvertedAcceleration's user avatar
561 votes
18 answers
239k views

List<T> or IList<T> [closed]

Can anyone explain to me why I would want to use IList over List in C#? Related question: Why is it considered bad to expose List<T>
Peanut's user avatar
  • 19.2k
553 votes
9 answers
87k views

Why does C# forbid generic attribute types?

This causes a compile-time exception: public sealed class ValidatesAttribute<T> : Attribute { } [Validates<string>] public static class StringValidation { } I realize C# does not ...
Bryan Watts's user avatar
  • 45.2k
544 votes
6 answers
155k views

Possible heap pollution via varargs parameter

I understand this occurs with Java 7 when using varargs with a generic type; But my question is.. What exactly does Eclipse mean when it says "its use could potentially pollute the heap?" And How ...
hertzsprung's user avatar
  • 9,714
536 votes
15 answers
437k views

Deserialize a List<T> object with Gson?

I want to transfer a list object via Google Gson, but I don't know how to deserialize generic types. What I tried after looking at this (BalusC's answer): MyClass mc = new Gson().fromJson(result, new ...
jellyfish's user avatar
  • 7,948
502 votes
11 answers
502k views

What is SuppressWarnings ("unchecked") in Java?

Sometime when looking through code, I see many methods specify an annotation: @SuppressWarnings("unchecked") What does this mean?
jojo's user avatar
  • 13.7k
501 votes
12 answers
479k views

ArrayList vs List<> in C#

What is the difference between ArrayList and List<> in C#? Is it only that List<> has a type while ArrayList doesn't?
scatman's user avatar
  • 14.3k
500 votes
7 answers
176k views

What is the point of the diamond operator (<>) in Java?

The diamond operator in java 7 allows code like the following: List<String> list = new LinkedList<>(); However in Java 5/6, I can simply write: List<String> list = new LinkedList()...
tofarr's user avatar
  • 7,752
499 votes
1 answer
344k views

C# generics syntax for multiple type parameter constraints [duplicate]

Possible Duplicate: Generic methods and multiple constraints I need a generic function that has two type constraints, each inheriting from a different base class. I know how to do this with one ...
Jon B's user avatar
  • 51.5k
485 votes
10 answers
797k views

List<T> OrderBy Alphabetical Order

I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic List<T>. For the sake of this example, let's say I have a List of a Person type with a property of lastname. How would I ...
SaaS Developer's user avatar
484 votes
17 answers
264k views

Passing arguments to C# generic new() of templated type

I'm trying to create a new object of type T via its constructor when adding to the list. I'm getting a compile error: The error message is: 'T': cannot provide arguments when creating an instance ...
LB.'s user avatar
  • 13.9k
484 votes
22 answers
462k views

A generic list of anonymous class

In C# 3.0 you can create anonymous class with the following syntax var o = new { Id = 1, Name = "Foo" }; Is there a way to add these anonymous class to a generic list? Example: var o = new { Id = ...
DHornpout's user avatar
  • 6,470
466 votes
24 answers
157k views

Is there a constraint that restricts my generic method to numeric types?

Can anyone tell me if there is a way with generics to limit a generic type argument T to only: Int16 Int32 Int64 UInt16 UInt32 UInt64 I'm aware of the where keyword, but can't find an interface for ...
Corin Blaikie's user avatar
464 votes
20 answers
138k views

Passing a single item as IEnumerable<T>

Is there a common way to pass a single item of type T to a method which expects an IEnumerable<T> parameter? Language is C#, framework version 2.0. Currently I am using a helper method (it's ....
vgru's user avatar
  • 50.6k
454 votes
11 answers
63k views

What are the reasons why Map.get(Object key) is not (fully) generic

What are the reasons behind the decision to not have a fully generic get method in the interface of java.util.Map<K, V>. To clarify the question, the signature of the method is V get(Object ...
WMR's user avatar
  • 12.9k
437 votes
2 answers
193k views

Java Generics With a Class & an Interface - Together

I want to have a Class object, but I want to force whatever class it represents to extend class A and implement interface B. I can do: Class<? extends ClassA> Or: Class<? extends ...
Alex Beardsley's user avatar
435 votes
8 answers
234k views

Method has the same erasure as another method in type

Why is it not legal to have the following two methods in the same class? class Test{ void add(Set<Integer> ii){} void add(Set<String> ss){} } I get the compilation error Method ...
Omry Yadan's user avatar
  • 32.5k
416 votes
3 answers
131k views

How does the reified keyword in Kotlin work?

I'm trying to understand the purpose of the reified keyword. Apparently, it's allowing us to do reflection on generics. However, when I leave it out, it works just as fine. When does this make an ...
hl3mukkel's user avatar
  • 5,689
407 votes
14 answers
144k views

Can't operator == be applied to generic types in C#?

According to the documentation of the == operator in MSDN, For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For ...
Hosam Aly's user avatar
  • 42.1k
401 votes
11 answers
174k views

What does "where T : class, new()" mean?

Can you please explain to me what where T : class, new() means in the following line of code? void Add<T>(T item) where T : class, new();
Rawhi 's user avatar
  • 6,363
393 votes
12 answers
296k views

Using Mockito to mock classes with generic parameters

Is there a clean method of mocking a class with generic parameters? Say I have to mock a class Foo<T> which I need to pass into a method that expects a Foo<Bar>. I can do the following ...
Tim Clemons's user avatar
  • 6,341
377 votes
4 answers
199k views

Case insensitive access for generic dictionary

I have an application that use managed dlls. One of those dlls return a generic dictionary: Dictionary<string, int> MyDictionary; The dictionary contains keys with upper and lower case. ...
TocToc's user avatar
  • 4,889
370 votes
9 answers
240k views

Why is "extends T" allowed but not "implements T"?

Is there a special reason in Java for using always "extends" rather than "implements" for defining bounds of type parameters? For example: public interface C {} public class A<B ...
user120623's user avatar
  • 3,701
368 votes
13 answers
326k views

Nullable type as a generic parameter possible?

I want to do something like this : myYear = record.GetValueOrNull<int?>("myYear"), Notice the nullable type as the generic parameter. Since the GetValueOrNull function could return null my ...
Tom Pester's user avatar
  • 3,723
356 votes
14 answers
123k views

Null or default comparison of generic argument in C#

I have a generic method defined like this: public void MyMethod<T>(T myArgument) The first thing I want to do is check if the value of myArgument is the default value for that type, something ...
Stefan Moser's user avatar
  • 6,813
356 votes
16 answers
191k views

Check if a class is derived from a generic class

I have a generic class in my project with derived classes. public class GenericClass<T> : GenericInterface<T> { } public class Test : GenericClass<SomeType> { } Is there any way ...
bernhardrusch's user avatar
353 votes
12 answers
536k views

What causes javac to issue the "uses unchecked or unsafe operations" warning

For example: javac Foo.java Note: Foo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
user avatar
344 votes
8 answers
92k views

IEnumerable and Recursion using yield return

I have an IEnumerable<T> method that I'm using to find controls in a WebForms page. The method is recursive and I'm having some problems returning the type I want when the yield return is ...
Jamie Dixon's user avatar
  • 53.7k
336 votes
4 answers
136k views

Generic method with multiple constraints

I have a generic method which has two generic parameters. I tried to compile the code below but it doesn't work. Is it a .NET limitation? Is it possible to have multiple constraints for different ...
Martin's user avatar
  • 40k
328 votes
12 answers
354k views

Create instance of generic type whose constructor requires a parameter?

If BaseFruit has a constructor that accepts an int weight, can I instantiate a piece of fruit in a generic method like this? public void AddFruit<T>()where T: BaseFruit{ BaseFruit fruit = ...
Boris Callens's user avatar
325 votes
6 answers
207k views

What is the difference between 'E', 'T', and '?' for Java generics?

I come across Java code like this: public interface Foo<E> {} public interface Bar<T> {} public interface Zar<?> {} What is the difference among all three of the above and what ...
ace's user avatar
  • 11.8k
319 votes
16 answers
233k views

What's the reason I can't create generic array types in Java?

What's the reason why Java doesn't allow us to do private T[] elements = new T[initialCapacity]; I could understand .NET didn't allow us to do that, as in .NET you have value types that at run-time ...
devoured elysium's user avatar
316 votes
15 answers
405k views

Get generic type of java.util.List

I have; List<String> stringList = new ArrayList<String>(); List<Integer> integerList = new ArrayList<Integer>(); Is there a (easy) way to retrieve the generic type of the ...
Thizzer's user avatar
  • 16.4k

1
2 3 4 5
1023