What's the difference between these two java variable declarations?

后端 未结 5 1717
小蘑菇
小蘑菇 2020-12-21 17:10
public class SomeClass {
    private HashSet contents = new HashSet();
    private Set contents2 = new HashSet&         


        
5条回答
  •  心在旅途
    2020-12-21 17:54

    Set is an interface, and HashSet is a class that implements the Set interface.

    Declaring the variable as type HashSet means that no other implementation of Set may be used. You may want this if you need specific functionality of HashSet.

    If you do not need any specific functionality from HashSet, it is better to declare the variable as type Set. This leaves the exact implementation open to change later. You may find that for the data you are using, a different implementation works better. By using the interface, you can make this change later if needed.

    You can see more details here: When should I use an interface in java?

提交回复
热议问题