There is no Java language command to do that but the Java collection classes allow one to bypass the problem. If you can't use the collection classes which do this behind the scenes then you will have to do what they do and allocate a new array the length you want, populate it from the content of the original array and then replace the original with the new. This can be done with one line by using the static members of java.util.Array.
Retired horse trader.
Note: double-underline links may be advertisements automatically added by this site and are probably not endorsed by me.
siva venkata prasad
Joined: Jul 14, 2011
actually.. I was asked to implement "Queue" functionality using Arrays and with out using any API.. and emphasized on how can I make arrays dynamic with out any collection API?
write code that takes an array, finds how big it is, create a new array that is larger (by whatever size you feel necesarry), then copy the elements in to your new array, then return the reference to that new array.
Each time you try and add something to your array, you'll have to check and see if it is full or not. If so, call your method, THEN add it. If it's not full, just add it.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Remember that in java arrays are static in nature. once we created an array, we are not supposed to increase or decrease the size. that is, of course, the drawback of arrays. To achieve this thing only we go for collection frame work, where you can use Arrays class, so that you can add more elements to that as the collection classes are dynamic in nature. We don't bother about the size in collections
You could do that with a circular array. You have input and retrieval indices. Whenever anything is "offer"ed to the Queue, you increment your input index. If your input index reaches the size of the array, you use the % operator to bring it back to the beginning. If your input index catches up with the retrieval index, you can enlarge the array, or throw an Exception.
Whenever you "poll" anything, you increment the retrieval index (and assign the removed value in the array to null). If the retrieval index catches up with the input index, you throw an Exception. If the retrieval index reaches the size of the array, you use the % operator to go back to the beginning.
Note, instead of using the % operator you can use the & operator and ensure the size of the array is always an exact power of 2.