Java - Using "<? extends Interface>" vs Interface only [duplicate] - java

This question already has answers here:
Whats the use of saying <? extends SomeObject> instead of <SomeObject>
(5 answers)
Closed 6 years ago.
I have seen some code as follows
public interface IBean {
}
and its usage at some places as
public void persist(List<? extends IBean> beansList) {
}
However same can achieved with following code
public void persist(List<IBean> beansList) {
}
So what is the difference between both methods, both are excepting objects that must inherit IBean interface?
Here are the bean classes
public class Category implement IBean {
//related fields
}
public class Product implement IBean {
//related fields
}

You can pass a List<Category> to public void persist(List<? extends IBean> beansList), but you cannot pass a List<Category> to public void persist(List<IBean> beansList).
On the other hand, you can pass a List<IBean> to both methods.

The reason is that generics are invariant. This means for example that you can't use a List<Integer> where a List<Number> is expected.
But when turning to wildcards, you can circumvent that restriction. Therefore, when you really have a List<Product> you will not be able to pass that into a method that expects List<IBean> - you would have to somehow convert the list first. To be precise: you would do a "hard" cast; as there is no point in "converting" generic lists, as type erasure kicks in at runtime anyway!
By using the wildcard on the method definition, you can allow for passing Lists that use "real" sub classes of the extended type; without the need of ugly casts.

Related

Why cannot be inherited with different type arguments [duplicate]

This question already has answers here:
How to implement the same interface multiple times, but with different generics? [duplicate]
(3 answers)
Closed 6 months ago.
I have seen many question around this, but none seens to be exactly what I am facing and I still don't understand what's wrong.
I have a class that implements two interfaces and these two interfaces extends from another interface with generics. Whoever it seens like I can't implement these two interfaces in the same class, as I have an error saying 'cannot be inherited with different type arguments'.
Interface with Generics:
public interface Observer<O> {
void onEvent(O data);
}
Interface A:
public interface EventAObserver extends Observer<String> {
}
Interface B:
public interface EventBObserver extends Observer<Integer> {
}
Class that needs to listen both events and gets the error:
public class Listener implements EventAObserver, EventBObserver {
#Override
public void onEvent(Integer data) {
}
#Override
public void onEvent(String data) {
}
}
All this trouble because somewhere else in my code I have a list of observers and I want to broadcast events just like:
for (Observer observer : observers)
observer.onEvent(data);
Is it possible to solve this inheritance problem? Or should I try something entirely diffent?
Thanks!
You should try something different because of type erasure for generics during runtime. This means during runtime the specified types for generics all are replaced by Object. And therefore the onEvent methods in Listener look the same during runtime.

Generics in java at method level [duplicate]

This question already has answers here:
Why does this Java method appear to have two return types?
(3 answers)
Closed 6 months ago.
I am new to java. I am trying to debug a code and not able to understand one line.
public interface CommandDispatcher {
<T extends BaseCommand> void registerHandler(Class<T> type, CommandHandlerMethod<T> handler);
void send(BaseCommand command);
}
I know generics but not able to understand below line.
<T extends BaseCommand> void registerHandler(Class<T> type, CommandHandlerMethod<T>)
what is <T extends BaseCommand> before void also I am not ablr to understand Class<T>
Can somebody explain me to understand the above line. Consider BaseCommand is an interface.
<T extends BaseCommand> means at the calling side Type T can be BaseCommand OR derived from BaseCommand class/interface.
Class<T> type means the first argument should be the type of Class T.
class Command extends BaseCommand{
}
then you can call like this
registerHandle( Command.class, ...);
So that inside implementation one can create instance of Type Command.

Generic type of superclass property lost in subclass with no type bound [duplicate]

This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 4 years ago.
Here is a pathological generics example in Java. What is going on here?
public abstract class Foo<X> {
private List<String> stuff;
public List<String> getStuff() {
return stuff;
}
public void setStuff(List<String> stuff) {
this.stuff = stuff;
}
}
Then I created a subclass, but not I did not specify the type bound, which should make it object.
public class Bar extends Foo {
public Bar() {
setStuff(new ArrayList<>());
}
public void whatIsGoingOnHere() {
for(String thing : getStuff())
System.out.println("Why is this a compiler error???");
}
}
Why is this a compiler error?
You call setStuff(new ArrayList<>());. Here ArrayList<> isn't not bound, it is inferred by the compiler if it can. And it can as setStuff is setStuff(List<String>). So the compiler knows it is a ArrayList<String> and uses (infers) that.
Your loop iterates over an List<String> as returned by the getStuff() method, so defining the thing as a String (or any super class or interface) will be okay for the compiler.
The base class does have an X type, but it doesn't matter as your stuff list is declared with a type. Only if you would define stuff as an List<X> it would matter what the subclass defined for X.

Up-casting template argument types [duplicate]

This question already has answers here:
Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?
(19 answers)
Closed 7 years ago.
Why does Java not support automatic up-casting for template argument types?
For example, the following class will not compile unless the newly created Derived instance will be manually casted to a Base instance:
public class Example implements Iterable<Base> {
#Override
public Iterator<Base> iterator() {
return Arrays.asList(new Derived()).iterator();
}
private class Base {
}
private class Derived extends Base {
}
}
No need to cast.
The problem here is that Arrays.asList(new Derived()) naturally tries to create a List<Derived>,
and then calling .iterator() on a List<Derived> naturally gives an Iterator<Derived>,
which is not a sub-type of Iterator<Base>, so you get a compilation error.
You can specify that you want a List<Derived>, using Arrays.<Base>asList.
This works,
because you can certainly put a Derived instance into a List<Base>,
and then calling .iterator() on a List<Base> naturally gives an Iterator<Base>.
class Example implements Iterable<Base> {
#Override
public Iterator<Base> iterator() {
return Arrays.<Base>asList(new Derived()).iterator();
}
}

Class using generics is calling wrong version of method (superclass rather than subclass)? [duplicate]

This question already has answers here:
Java generics type erasure: when and what happens?
(7 answers)
Closed 7 years ago.
I am trying to refactor some code, moving common code shared among a few caches to a base class. Here's a simplified concept of it:
public abstract class DBObject {
public void copyTo(DBObject other) {
other.setId(this.id);
}
}
public class Person extends DBObject {
public void copyTo(Person other) {
super.copyTo(other);
other.setName(this.name);
}
}
public class PersonCache extends Cache<Person> {
}
public abstract class Cache<T extends DBObject> {
Map<Long, T> idToCachedMap;
private Class<T> tObjectClass;
public void initialize() {
// does stuff to populate the idToCachedMap
}
public void updateCache(T cachedObjToUpdate) {
T cachedObj = idToCachedMap.get(cachedObjToUpdate.getId());
T oldCachedObj = tObjectClass.newInstance();;
cachedObj.copyTo(oldCachedObj); // PROBLEM HERE
// do other stuff...
}
}
The problem I'm running into is that when I call updateCache(Person) on a PersonCache, the copyTo methods that get invoked on the objects are that in DBObject, as opposed to the one in Person. As a result, only some of the data is actually copied (in this example case, the ID, but not the name).
It seems to me that since both cachedObj and oldCachedObjs are guaranteed to be Person objects if it's a PersonCache, the copyTo method that should be called is the one on the Person class.
I feel like there must be something about how generics work that I'm missing that is causing this behavior. I know if I override copyTo in the Person class to be a signature of copyTo(DBObject other) rather than copyTo(Person other) it then does call the copyTo on the person class - but that'd be a sloppy way to rewrite it and I think I'm missing something that might be cleaner.
You are not overwriting the copyTo method because you change the signature. And you invoke the method which exist in T.
Try this:
public abstract class DBObject<T extends DBObject> {
public void copyTo(T other) {
other.setId(this.id);
}
}
public class Person extends DBObject<Person> {
#Override
public void copyTo(Person other) {
super.copyTo(other);
other.setName(this.name);
}
}
You state It seems to me that since both cachedObj and oldCachedObjs are guaranteed to be Person objects if it's a PersonCache, the copyTo method that should be called is the one on the Person class.
Because of type erasure this is an incorrect assumption, at runtime all it knows is DBObject and obviously Object as well.
It knows nothing about T at runtime, it is erased and not available at runtime.
copyTo(T other) is not equivlent to copyTo(Person other) they are overloaded not overridden because of the type erasure. copyTo(T other) actually becomes copyTo(DBObject other) as your behavior is showing that it matches copyTo(DBObject other). This is the expected behavior.
Type Erasure behavior is very well documented here on SO and on the internet in general.

Categories

Resources