0

I'm almost sure that the answer for this question is yes, but I'm not sure how to articulate it on my exam. Since an ArrayList is a List and a List is a Collection, we can definitely say that an ArrayList is a Collection.

However, how can I afirm that an ArrayList<String> is a Collection<String> without knowing that Collection is a generic class beforehand?

How would you answer this question?

Thanks

Nikos Paraskevopoulos
  • 39,514
  • 12
  • 85
  • 90
  • The term for what you ask is "variance" and has 3 ... variants: Covariance, contravariance and invariance. It is a confusing topic I must admit, but there are plenty of resources online. The `ArrayList` - `Collection` is a trivial example. More interesting case is `ArrayList` - `Collection`. – Nikos Paraskevopoulos Feb 14 '22 at 08:22

1 Answers1

0

Try this, for example at https://www.programiz.com/java-programming/online-compiler/ or https://www.tutorialspoint.com/compile_java_online.php:

import java.util.Collection;
import java.util.List;
import java.util.ArrayList;


public class Is_A_List_A_Class_class{

     public static void main(String []args){
        List<String> list = new ArrayList<String>();
        System.out.println(list instanceof Collection);
     }
}

Output:

> java -cp /tmp/K2aGszTI3o Is_A_List_A_Class_class
true
CiaPan
  • 9,381
  • 2
  • 21
  • 35