| Author |
Dynamic Array code
|
Sumit Suresh Rao
Greenhorn
Joined: Feb 16, 2009
Posts: 10
|
|
In an interview I was asked to write a code for dynamic array. Though I managed something I was not sure it was optimal. The following is somewhat similar to what I had attempted. Can someone help me iron out problems, if any, in the following code.
|
 |
Winston Gutkowski
Bartender
Joined: Mar 17, 2011
Posts: 4901
|
|
Sumit Suresh Rao wrote:Can someone help me iron out problems, if any, in the following code.
The only major error I see is that incrementArr() is public, which means that anyone can run it and supply an array of their own.
There are, however, a few minor points:
getArray() returns a direct reference to dynArray, which means that anyone can then update it. In cases like this it's usually better to return a copy.addElement() increases the size of the array after adding, which means that it may be doing unnecessary work (the method may never be called again).Your 'size' field is basically redundant, since except for one statement, it holds the same value as dynArray.length.Your use of the term "size" is unconventional. In general, the Java Collections API defines "size" as the current highest element (ie, your 'index'). Your 'size' field is normally called "capacity".
HIH
Winston
|
Isn't it funny how there's always time and money enough to do it WRONG?
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32830
|
|
Welcome to the Ranch
In addition ot what Winston told you, I trust you pointed out there is no such thing as a dynamic array and that you need to replace the array with a new one rather than changing its size.
|
 |
Sumit Suresh Rao
Greenhorn
Joined: Feb 16, 2009
Posts: 10
|
|
Thank you Winston Gutkowski.
there is no such thing as a dynamic array
@Campbell, just wanted an array to exhibit dynamic behaviour.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32830
|
|
|
You should not let people get away with sloppy nomenclature. Remember if that is an interview question, they would expect you to say there is no such thing as a dynamic array. Such questions are worded to trap you.
|
 |
Sumit Suresh Rao
Greenhorn
Joined: Feb 16, 2009
Posts: 10
|
|
|
Thanks @Campbell Ritchie
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32830
|
|
You’re welcome
|
 |
 |
|
|
subject: Dynamic Array code
|
|
|