Create a List of primitive int?

In Java the type of any variable is either a primitive type or a reference type. Generic type arguments must be reference types. Since primitives do not extend Object they cannot be used as generic type arguments for a parametrized type. Instead use the Integer class which is a wrapper for int: List<Integer> list = new ArrayList<Integer>(); If your using … Read more

Java comparing generic types

You cannot overload operators in Java. The < operator only applies to primitive (or numeric) types, not reference types. Since T is a type variable that represents a reference type, you cannot use < on variables of type T. You have to use if (item.compareTo(bn.item) < 0) check the value returned and decide to do … Read more

How to create a generic array in Java?

I have to ask a question in return: is your GenSet “checked” or “unchecked”? What does that mean? Checked: strong typing. GenSet knows explicitly what type of objects it contains (i.e. its constructor was explicitly called with a Class<E> argument, and methods will throw an exception when they are passed arguments that are not of type E. See Collections.checkedCollection.-> in that case, you should … Read more

Instantiating object of type parameter

After type erasure, all that is known about T is that it is some subclass of Object. You need to specify some factory to create instances of T. One approach could use a Supplier<T>: class MyClass<T> { private final Supplier<? extends T> ctor; private T field; MyClass(Supplier<? extends T> ctor) { this.ctor = Objects.requireNonNull(ctor); } public void myMethod() { field … Read more

How do I make the method return type generic?

You could define callFriend this way: public <T extends Animal> T callFriend(String name, Class<T> type) { return type.cast(friends.get(name)); } Then call it as such: jerry.callFriend(“spike”, Dog.class).bark(); jerry.callFriend(“quacker”, Duck.class).quack(); This code has the benefit of not generating any compiler warnings. Of course this is really just an updated version of casting from the pre-generic days and … Read more

Error: Generic Array Creation

You can’t create arrays with a generic component type. Create an array of an explicit type, like Object[], instead. You can then cast this to PCB[] if you want, but I don’t recommend it in most cases. PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */ If you want type safety, use a collection like java.util.List<PCB> instead of an … Read more