Adding objects to a fixed Array in Java -
up till i've been using arraylists. i've used arrays once used differently how i'm suppose now. have class called member
, looks this:
public class member { private string firstname; private string lastname; private int monthjoined; private int yearjoined; }
of course class has accessor/ mutator methods , constructors below.
now have make class called club can hold fixed number of members stored in member[] array. (the fixed number can number) @ point i'm wondering variable like. class need method titled public void join(member member) adds member club, new members added first null index in array.
i know how work arraylist not array. given class club variable , method like?
i discourage using array when arraylist
job better. in general, in java, collections (e.g. arraylist
) preferred array, unless specific circumstances dictate otherwise.
the main disadvantage of arrays size must fixed @ time of initialization , remains long reference array remains available. thus, if club
may contain 1000
members in next 5 years, need allocate 1000
members right now. moment 1001st member joins, have allocate new , improved array, copy existing members , use new array. , more done arraylist
transparently.
having said that, using array should straightforward:
class club { //thread unsafe private member[] members; private int ncurrentmembers = 0; club(int initialcapacity) { //validate initialcapacity members = new member[initialcapacity]; } public boolean join(member m) { //validate m if (ncurrentmembers == members.length) { members = arrays.copyof(members, members.length + 100); } members[ncurrentmembers++] = m; return true; } public boolean leave(member m) { // homework :-) return true; } }
Comments
Post a Comment