Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interview Question

 
Mani vannan
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to create array that can store 'n' number of elements? (without specifying the size)

(We are able to store 'n' number of elements dynamically using java.util.LinkedList, ArrayList right? How are they implemented to adopt any number of elements dynamically?)
 
Chetan Raju
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess even the collection classes uses arrays in the background which is not transparent to users.
 
Mani vannan
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yeah, thats what I am talking about. If anybody having jdk1.3 or less version, please post here the source code for java.util.ArrayList (jdk1.3 version)..
 
Mani vannan
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it. The collection starts with a fixed capacity. If the the elements size exceed than the current capacity, they are moved to a higher larger object array. previous one destroyed (nullified).

Thanks guys!
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, some collections do that. Some don't. I'd guess a LinkedList is not backed by an array at all.
 
Srinivas Kalvala
Ranch Hand
Posts: 257
Firefox Browser Hibernate Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello friends,

One has to specify the size for normal arrays. The Collection class ArrayList is a wrapper over Object []. With Decorator pattern it is extending the functionality of the general arrays.

If you observe the java source, the constructor for arraylist is ,

/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this(10);
}

And

/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
private transient Object elementData[];

/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;



So, I think you got very clear view.

Thank you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic