This isn't a question that I am expecting a specific answer to since it is pretty broad. I'm teaching myself Java and am focusing specifically on dynamic memory allocation. Let's make a very oversimplified example: Say that I have a really basic data entry screen. So basic that all that happens is the user enters a series of first names, maybe for an employee directory or something. On my JFrame, I have a single JTextField control where these names are entered. The number of employees is known only at run time. The user enters a name and hits the enter key, which commits the name to memory and creates a new object to store the next name (silly, I know, but I'm trying to focus). Something like this (don't take this too literally - I obviously didn't compile this):
public class Employee {
String fName;
public void setName( String n ) {
fName = n;
}
};
public class JFrameEmp {
//blah, blah, blah
JTxtName.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
/* Handle the enter key */
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
/* Store name */
this.setName(JTxtName.getText());
/* Create New Object */
Employee next = new Employee();
}
};
}
}
Where I need help is on the last line. Even if this were to work, let's say that I wanted to print out a list of the names entered. In my approach, I see no way to uniquely identify each object (so that I can iterate through them).
Do I need to create an array to store these? But that has a fixed length and lives on the stack. I'd rather find a way to use the heap to allow for an open-ended list.
What should I be reading to learn how to do this? It must be a very common thing to do, but the books that I have don't seem to cover it.
Thanks. I hope that I have explained this well enough without going into too much detail.
Map<K,V>interface?