0

What is the time complexity of initializing an arraylist?

Arraylist<E> A = new Arraylist<E>

What about:

Arraylist<Integer> B = new ArrayList<>(Arrays.asList(1,2,3,4,5)

For the first option, I believe it would be O(1) constant time. However the second option is what I have trouble thinking about.

Makoto
  • 104,088
  • 27
  • 192
  • 230
FabolousPotato
  • 65
  • 1
  • 10

1 Answers1

2

Arrays.asList - just this one would be O(1). Under the hood a new ArrayList is created with the given array - no matter of the size of the array.

Or simpler, the same action happens all the time no matter the size of the array = it's constant.

When you do new ArrayList(Arrays.asList...), internally it copies the data:

....
elementData = Arrays.copyOf(elementData, size, Object[].class);

that will ultimately call System::arrayCopy; and this is where it gets tricky. In general, that could be thought as O(n), but since that is a native method is could be implemented as a single CPU instruction; thus becoming O(1).

I would still go with O(n) as the answer.

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • If the basic operation is copying or assigning this may not be true. – kelalaka Oct 03 '18 at 08:06
  • @kelalaka plz offer some details too, I am more than eager to read other opinions. .. – Eugene Oct 03 '18 at 08:08
  • Since the Arraylist creating and assigning is the problem here, the basic operation must be allocating or assigning or copy depend on the method. Otherwise, one can simply say that memory operations are constant compared to addition etc. – kelalaka Oct 03 '18 at 08:11
  • @kelalaka good point! in your opinion, what would the complexity than be? You could post an answer too, would very much like to read it – Eugene Oct 03 '18 at 08:16
  • There is a speed up here;http://www.danielvik.com/2010/02/fast-memcpy-in-c.html, but it is still constant. so (O(n). https://stackoverflow.com/questions/17498743/how-does-the-internal-implementation-of-memcpy-work – kelalaka Oct 03 '18 at 08:38
  • @kelalaka wait, if you say still constant, do you mean `O(1)`? – Eugene Oct 03 '18 at 08:39
  • What I try to say, for example when calculating the time complexity of an algorithm we just calculate over the basic operation. On Copying array, it should be O(n) since at the and you can copy at most a couple of memory by the system internals in the low level. n/c that all. – kelalaka Oct 03 '18 at 08:45