Java Generics, Returnable General Extension

Why am I not allowed to do this?

public abstract class A {} public class B extends A {} ... public ArrayList<A> foo() { return new ArrayList<B>(); } 

I switched to publish because there are so many people who like to point out stupid mistakes.

Why should I write ALL this code. Just to satisfy Java insensitivity?

 public List<A> foo() { List<A> aList = new ArrayList<A>(); List<B> bList = new ArrayList<B>(); /* fill bList*/ for (B b : bList) { aList.add(b); } return aList; } 
+4
source share
3 answers

An ArrayList<B> not an ArrayList<A> . For example, you cannot add an arbitrary A . Or how I like to think about it: a bunch of bananas is not a fruit. When you try to add an apple to a bunch of bananas, it rolls back ...

You can use wildcards to make it work:

 public ArrayList<? extends A> foo() { return new ArrayList<B>(); } 

See the Java Generics FAQ for more details.

EDIT: To answer your specific question, why you need to write all this extra code, you do not. Just create an ArrayList<A> inside foo() to start. There is no need to copy the contents of one list to another.

If you still mind Java behavior, what would you like to do with the following code?

 // Doesn't compile, fortunately... List<String> strings = new List<String>(); List<Object> objects = strings; objects.add(new Date()); String string = strings.get(0); // Um, it a Date, not a String... 
+12
source

a) First, function does not exist in Java. Java methods have the format

 modifiers <type_parameters[,type_parameter]*>? return_type method_name ( [parameter[,parameter]*]? ) [throws exceptiontype[, exceptiontype]*]{ method_body } 

b) Here's how to do it:

 public List<? extends A> foo() { return new ArrayList<B>(); } 

c) I changed the method signature to List . It’s bad practice to have implementation types in the external API of your class if the corresponding interface exists.

+3
source

because ArrayList<B>() not ArrayList<A> . he does not extend from him

B extends A does not mean ArrayList<B>() extends ArrayList<A>()

+2
source

Source: https://habr.com/ru/post/1335073/


All Articles