1

I'm trying to add a new Entry object to an array of objects. I don't know how I would go about writing a method to do this. Also I'd like to increase the size of the array as new elements are added to it.

public class Entry {

    private String surname, initial, extension;

    public Entry() { }

    public Entry(String surname, String initial, String extention) {
        this.surname = surname;
        this.initial = initial;
        this.extension = extention;
    }
}

I want to write the method to add the elemets to the array here. The new Entry object is currently hard coded but this will obviously be altered.

public class ArrayDirectory implements Directory {

    Entry[] entries = new Entry[4];


    public void addEntry(Entry newEntry) {
        newEntry = new Entry("isajas","ssds", "sasdas");

    }
}

Thank you for taking the time to read my question!

1
  • 1
    Have you considered using an ArrayList<Entry> rather than rolling your own dynamic array? Commented Apr 12, 2014 at 20:48

3 Answers 3

1

Here's how you do exactly what you're asking:

public class ArrayDirectory implements Directory {
    Entry[] entries = new Entry[1];

    public void addEntry(Entry newEntry) {
        Entry[] temp = new Entry[entries.length + 1];
        for (int i = 0; i < entries.length; i++) {
            temp[i] = entries[i];
        }
        newEntry = new Entry("isajas","ssds", "sasdas");
        temp[temp.length - 1] = newEntry;
        entries = temp;
      }
}

But as many suggested, ArrayList (or even Vector) would be a better choice than trying to reinvent the wheel here.

Sign up to request clarification or add additional context in comments.

Comments

1

Consider using java.util.ArrayList instead. It is a "resizable-array implementation of the List interface" and provides an easy-to-use API for adding objects, e.g. ArrayList<Type>().add(Object o). Have a look at the Javadoc link above, it's really handy and I use it a lot.

It also saves you the extra work of assigning temporary arrays to-and-fro and creating extra objects...

Comments

0

You can maintain a variable which tells you the number of Entries present in the directory. Every time you add/remove an entry just update this variable. Effectively you are implementing a Stack.

public class ArrayDirectory implements Directory {

  Entry[] entries = new Entry[4];
  private int numEntries = 0;

  public void addEntry(Entry newEntry) {
    if (numEntries == 4) { /* Display an error */ }

    newEntry = new Entry("isajas","ssds", "sasdas");
    entries[numEntries] = newEntry;
    numEntries++;
  }
}

Or alternatively you can java's inbuilt ArrayList data structure to add/remove entries.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.