Placing a List in the parameters of another List in java
Sorry if the title is unclear, but I wasn't exactly sure how to describe this in that little amount of words. Okay, so suppose we have this declaration:
ArrayList<String> list = new ArrayList<String>();
//add items to list
Set<String> set = new TreeSet<String>(list);
Now, from what I understand, set
will receive the data from list
and sort them because that's what TreeSets do. However, on the oracle website, I don't see any constructor in the HashSet class that takes a List as a parameter. So, I don't understand why this works if there is n开发者_运维问答o defined constructor to accept a List as a parameter.
TreeSet
has a constructor that takes a Collection
, and List
is a Collection
(List
extends Collection
).
Many classes in the Java collections framework follow the same concept. ArrayList
, for instance, also has a constructor that takes a Collection
. This makes it easy to copy data between collections.
Take a look at TreeSet(Collection c). This accepts a Collection
and ArrayList
implements Collection
.
精彩评论