Skip to content

Tag: generics

trouble initialize List Using Arrays.asList

When I initialize List, I am able to do this: But when I want to simplify it using Arrays.asList: It cannot compile with error: Why it cannot do the type inference right and how to fix this? Answer Remember that … is just syntactic sugar for an array parameter. You can call a method with a variadic para…

Java instance for comparable

Why is it legal to create new Box(); and new Box<Integer>();? Is it because Box is comparable? Answer You have declared the class with a generic type parameter. This is not the same as implementing the Comparable interface: Is the same as: Which is not the same as: Because the type parameter is unbounde…

TreeSet constructor with Comparator parameter

In Java’s documentation for its class TreeSet one of the constructors is shown to have the following header: Can someone help explain why there is a constructor for TreeSet which takes a comparator object as its argument? I have no clue why this is done. Answer The elements in a TreeSet are kept sorted. If yo…

How to check does interface with generic fit to class

I have some interface with generic type interface DummyInterface<T> and i have class to which i have to set interface Imagine the situation where i store DummyClass with different generics in ArrayList. When i get class from list i don’t know the generic of class, and i want to check if interface …

Case-insensitive matching of a string to a Java enum

Java provides a valueOf() method for every Enum<T> object, so given an enum like one can do a lookup like If the string passed to valueOf() does not match (case sensitive) an existing Day value, an IllegalArgumentException is thrown. To do a case-insensitive matching, one can write a custom method insid…