Create instance of generic type in Java?

You are correct. You can’t do new E(). But you can change it to private static class SomeContainer<E> { E createContents(Class<E> clazz) { return clazz.newInstance(); } } It’s a pain. But it works. Wrapping it in the factory pattern makes it a little more tolerable.

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

How do I address unchecked cast warnings?

The obvious answer, of course, is not to do the unchecked cast. If it’s absolutely necessary, then at least try to limit the scope of the @SuppressWarnings annotation. According to its Javadocs, it can go on local variables; this way, it doesn’t even affect the entire method. Example: @SuppressWarnings(“unchecked”) Map<String, String> myMap = (Map<String, String>) … Read more

How do I clone a generic list in C#?

If your elements are value types, then you can just do: List<YourType> newList = new List<YourType>(oldList); However, if they are reference types and you want a deep copy (assuming your elements properly implement ICloneable), you could do something like this: List<ICloneable> oldList = new List<ICloneable>(); List<ICloneable> newList = new List<ICloneable>(oldList.Count); oldList.ForEach((item) => { newList.Add((ICloneable)item.Clone()); }); … Read more

Is List a subclass of List? Why are Java generics not implicitly polymorphic?

No, a List<Dog> is not a List<Animal>. Consider what you can do with a List<Animal> – you can add any animal to it… including a cat. Now, can you logically add a cat to a litter of puppies? Absolutely not. // Illegal code – because otherwise life would be Bad List<Dog> dogs = new ArrayList<Dog>(); … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)