Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Collections.unmodifiableList() time complexity

I am wondering what's the time complexity of Collections.unmodifiableList?

If I want to make an incoming Collection immutable, what's the cheapest way?

like image 698
CuriousMind Avatar asked Mar 03 '26 16:03

CuriousMind


2 Answers

I am wondering what's the time complexity of Collections.unmodifiableList?

Collections.unmodifiableList returns a view of its argument list as opposed to a copy, so it's O(1). This is typically how you'd create an immutable list, but be sure to not change the original mutable list, since those changes will be reflected in the newly created immutable list. This shouldn't be a problem if you keep the original list private. This is the situation I'm talking about:

List<String> modifiableList = new ArrayList<>();
List<String> unmodifiableList = Collections.unmodifiableList(modifiableList);

System.out.println(unmodifiableList);
modifiableList.add("hello");
System.out.println(unmodifiableList);
[]
[hello]

This happens because unmodifiableList is a view (and not a copy) of modifiableList.

like image 165
arshajii Avatar answered Mar 06 '26 07:03

arshajii


Time complexity for which operations?

For all non-modifying operations, it would be in the same O notation as the underlying data structure.

For all modifying operations, it probably would be just a bit faster (early error exiting).

like image 28
Edwin Buck Avatar answered Mar 06 '26 05:03

Edwin Buck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!