The ArrayList Notebook
Premium Content - Free Preview
You created a nice Note class, but now you need a class to store different Notes. In this node, we'll create a simple Class called Notebook
which will contain methods for adding, retrieving and listing notes. What structure should be used in Notebook to keep track of its Notes? We've learned about Arrays, so we'll start with a simple Class that uses an array to store Notes:
public class ArrayNotebook
{
private Note[] notes;
/** Constructor for objects of class Notebook */
public ArrayNotebook()
{
notes = new Note[10];
}
}
This code declares an array variable for holding Note objects. The constructor initializes an empty Note array with 10 cells.
Limitations of Array
You're now ready to create a method to add Notes to notes
, but you right away face the limitation of the simple array - there's no easy way to just add items to an array. You would need to create an index variable just to keep track of where to add the Notes. And what happens when you need to add more than 10 notes when the array is only 10 cells large? Things would get very messy.
public class ArrayNotebook
{
private Note[] notes;
private int index;
public ArrayNotebook()
{
notes = new Note[10];
index = 0;
}
public void addNote(Note note){
if(index < notes.length){
notes[index] = note;
index++;
}
}
}
End of Free Content Preview. Please Sign in or Sign up to buy premium content.
Comments
Lukas Dancak
Nov 11, 3:53 PMHi. There is diference between code here in article and code in BlueJ project. What is the right code ?
BlueJ:
private ArrayList notes;
This Article:
private ArrayList notes;
}
Lukas Dancak
Nov 11, 3:57 PMThe answer is in next node. Sory for question.
thales
Jul 11, 9:29 AMi cant figure it out at all, can anyone help me and just give the right awnsers?
Gary
Mar 1, 12:20 PMI must be missing something obvious.... why do neither of these work:
fruit.add(orange);
fruit.add(String orange);
Learneroo
Mar 1, 8:11 PMStrings need quotes.
catypus
Jun 15, 1:23 AMWow... so apparently I don't know what I'm doing here:
private ArrayList fruit = new ArrayList();
doesn't work. I understand that would only work INSIDE a class.
Maybe I just answered my own question.
Please confirm, why can't I call it private?
Learneroo
Jun 15, 7:28 AMThat's correct. When you're inside a method, every variable you declare can only be accessed inside the method, so you don't use the
private
modifier.