简体   繁体   English

声明ArrayList对象和List对象在时间和空间复杂度上有什么区别?

[英]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的实例:

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). 我知道使用后一种声明可以灵活地将实现从一个List子类更改为另一个List子类(例如,从ArrayList到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> . 对于上面列出的两个选项,您正在使用相同的数据结构实现,即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. 在您的示例中, list仍然是ArrayList ,因此行为不会改变。

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 ). 使用List<>声明而不是ArrayList<>意味着您将只使用通过List接口可见的方法,并且如果以后需要另一种类型的列表,则更改它很容易(您只需更改调用到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. 示例 :首先使用ArrayList但随后发现您经常需要删除列表中间的元素。 You would thus consider switching to a LinkedList . 因此,您将考虑切换到LinkedList If you used the List interface everywhere (in getter/setter, etc.), then the only change in your code will be: 如果在各处(使用getter / setter等)都使用List接口,则代码中的唯一更改将是:

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. 但是如果您使用ArrayList ,那么您将需要重构您的getter / setter签名,潜在的公共方法等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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