简体   繁体   中英

What is the difference in time & space complexity between declaring an ArrayList object and a List object?

I know that an instance of ArrayList can be declared in the two following ways:

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

and

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

I know that using the latter declaration provides the flexibility of changing the implementation from one List subclass to another (eg, from ArrayList to LinkedList).

But, what is the difference in the time and space complexity in the two? Someone told me the former declaration will ultimately make the heap memory run out. Why does this happen?

Edit: While performing basic operations like add, remove and contains does the performance differ in the two implementations?

The space complexity of your data structure and the time complexity of different operations on it are all implementation specific. For both of the options you listed above, you're using the same data structure implementation ie ArrayList<String> . What type you declare them as on the left side of the equal sign doesn't affect complexity. As you said, being more general with type on the left of the equal sign just allows for swapping out of implementations.

What determines the behaviour of an object is its actual class/implementation. In your example, the list is still an ArrayList , so the behaviour won't change.

Using a List<> declaration instead of an ArrayList<> means that you will only use the methods made visible by the List interface and that if later you need another type of list, it will be easy to change it (you just change the call to new ). This is why we often prefer it.


Example : you first use an ArrayList but then find out that you often need to delete elements in the middle of the list. You would thus consider switching to a LinkedList . If you used the List interface everywhere (in getter/setter, etc.), then the only change in your code will be:

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

but if you used ArrayList , then you will need to refactor your getter/setter signatures, the potential public methods, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM