-1

So my Java tutor at school just started to teach us about Containers and there's this little concept I don't understand about initialization.

Firstly, with ArrayList, what's the difference between these two ways for initializing:

ArrayList list = new ArrayList();

ArrayList<Car> list = new ArrayList<Car>();

Secondly, what's the difference between these two ways for initializing:

List<String> list = new ArrayList<String>();

ArrayList<String> list = new ArrayList<String>();

Or:

Set<String> list = new HashSet<String>();

HashSet<String> list = new HashSet<String>();

Or:

Map<Integer, String> list = new HashMap<Integer, String>();

HashMap<Integer, String> list = new HashMap<Integer, String>();

P.S. When I'm asking what's the difference, I mean how will it affect my liberty to use certain methods on the collection or shift the data that is stored in it.

Thanks!!

Chefi
  • 41
  • 4
  • 1
    While this question was closed for being a "duplicate", there is something is not really discussed on your second point on the linked preferred answers. When you initialize to an interface (i.e. `List list = new ArrayList();`) you gain the advantage of being isolated from changes made to the implementation of `List`. HOWEVER, any implementation specific methods of `ArrayList` are not accessible unless you cast the object to that type. There are some cases where this could be an issue. For the most part, you'd want to code to interfaces rather than concretions. – hfontanez Dec 07 '21 at 20:13

1 Answers1

0
ArrayList list = new ArrayList();
ArrayList<Car> list = new ArrayList<Car>();

The first does not specify a type (or called a raw type) and is no longer considered good practice. Always specify the type of object the list contains. By doing so the compiler will help you find certain bugs in your code at compile time rather than at run time.

List<String> list = new ArrayList<String>();
ArrayList<String> list = new ArrayList<String>();

The first assigns the instance to the List interface that has been implemented by the ArrayList class. The second is the class itself. It is recommended to use the interface over the class unless you need methods that the interface doesn't have. If you specify the interface it makes it easier to change to other implementations.

Set<String> list = new HashSet<String>();
HashSet<String> list = new HashSet<String>();

Same as for list. Set is the interface that HashSet implements.

Map<Integer, String> list = new HashMap<Integer, String>();
HashMap<Integer, String> list = new HashMap<Integer, String>();

Ditto.

Also, an implementation may implement several interfaces. And you may always assign the instance of the implementation to any of those interfaces. However, only the methods of that interface will be visible when you use such an assignment.

WJS
  • 36,363
  • 4
  • 24
  • 39