-4

I saw some code in Java that used code similar to

Collection<Cars> carsCollection = new ArrayList<>(); But I am a bit confused about the word Collection. 

I have a basic understanding of Collections in general, and how a list or queue is part of the collections but I am having a hard time understanding why they would use Collection<Cars> instead of ArrayList<Cars>. All the information I find on the internet about Collections is how lists and queues use them but I haven't seen much other code that uses the Collections keyword itself, most of them just implement arrays or lists or something else that is a part of the Collections framework. How do you use it or why use it? I tried casting it to an ArrayList like ArrayList<Cars> aList = new ArrayList<>(carsCollection) and it said their was an issue with casting it to an ArrayList.

  • 7
    It's not a keyword, it's an interface - [`Collection`](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/Collection.html) - all you've done is reduced the scope – MadProgrammer Jun 13 '22 at 06:44
  • 1
    (Scope in a non-technical sense ...) – Stephen C Jun 13 '22 at 06:50
  • Possibly related: [What does it mean to "program to an interface"?](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface). – Slaw Jun 13 '22 at 07:17

3 Answers3

1

As people have mentioned Collection is an interface, an interface in Java is a tool for abstraction. So the way to think about it is in terms of generality, where a Collection in this case is the most general term. Then you have, for example List, Map or Set which in turn are more specific abstractions of the idea of a Collection, finally you have the implementations for example ArrayList, HashSet and HashMap.

Generally you want to be as abstract as possible, i.e. using the most general abstraction that still fullfills the requirements that you have on your code.

In your example with Collection<Car> and ArrayList<Car> (which probably ought to be List<Car>), my guess would be that in the case of Collection<Car> that the code doesn't care about the order, because that isn't a requirement of the Collection abstraction, but in the case of the List abstraction it is.

I'd recommend that you read the javadoc for Collection and the other interfaces and implementations.

Daniel Figueroa
  • 10,348
  • 5
  • 44
  • 66
0

It is just an interface for a collections alike structures Lists, Sets,Maps etc. It denotes fact that this is a "collection" of object and exposes some specific methods.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
0

Doing this allows you to easily change the type of collection later. Maybe a LinkedHashSet yields better performance? This will be possible because your code is oblivious to the real type of collection and thus cannot call methods that aren’t available in all Collection types.

You might want to read up on the Collections Framework.

Kristof Neirynck
  • 3,934
  • 1
  • 33
  • 47