2

I came across this interview question about arraylist in Java, and I feel it is quite interesting but no clue how to answer it:

What attention should be paid when using arrayList to store large object?

I wonder if we should answer this question in the regard of time/space coplexity?

Thanks

Kevin
  • 6,711
  • 16
  • 60
  • 107
  • 5
    I think a ArrayList stores only references of the objects?! So it should not matter at all. – sk2212 Mar 13 '13 at 09:13
  • Was it a round-about way of asking about ArrayList's `ensureCapacity()` method? Might have meant large **numbers** of objects? – David Lavender Mar 13 '13 at 09:16
  • storing large objects isn't an issue but when you store a lot of objects, the array list could be inefficient, through reallocation of the array size. – rit Mar 13 '13 at 09:23

3 Answers3

8

All objects in Java are stored as references, in containers and variables, etc, so in C++ terms, all containers only store pointers to the objects. In such a situation, the size of the object should be irrelevant for most if not all use cases.

Karthik T
  • 31,456
  • 5
  • 68
  • 87
0

Internally ArrayList uses Object[]. Once it reaches max capacity, it creates a new array of size 1.5 times the original and will copy from old array to new array. May be interviewer wanted to check about the cost of this copy with large objects

ArrayList: how does the size increase?

check ensureCapacity() - http://www.docjar.com/html/api/java/util/ArrayList.java.html

Community
  • 1
  • 1
rajesh
  • 3,247
  • 5
  • 31
  • 56
0

ArrayList supports dynamic arrays that can grow as needed. In Java, arrays has a fixed length this means after the arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold. But, sometimes, you may dont know the size until the runtimeso that in this situation we used ArrayList. ArrayList can dynamically increase or decrease in size. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk. also, be aware that Arraylist store only objects.

user560401
  • 21
  • 2