Talk:SE251:Questions & Answers

From Marks Wiki
Revision as of 10:43, 3 November 2008 by Mark (talk | contribs) (2 revision(s))
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

When to use Arrays and Lists

Someone has suggested using arrays to represent the Transactions and suggested the following code.

private Transaction[] transactionHistory;
private int numberOfTransactions;
transactionHistory[ numberOfTransactions++ ] = new Transaction( ... );

There is one (big) problem with that - arrays are of fixed size. Once you initialize an array (giving its size or putting items into it) you cannot change the size of that array object. You can fake a dynamically expanding array using

System.arrayCopy(...)

method. But its very tedious and not a very efficient way of doing it. (e.g. you'll have to keep checking that the array is not yet full each time you are adding a Transaction object)


List (and any java.utils.Collection class) already takes care of this for you - so why try to re-invent the wheel?

Remember these two simple guidelines when deciding what data structure to use to represent a group of objects:

  • Use arrays (fixed size) if your collection's size is not going to change
  • Use a List (e.g. ArrayList, Vector etc) if your collection will change in size (or you don't know its size when you are initializing the instance).