Use Java to implement Notepad functionality. Start by listing the features that Notepad requires:
- You can add records (strings);
- The number of record bars can be obtained;
- One of the records can be deleted;
- A record of the specified section may be obtained;
- You can list all the records.
If this notepad is part of a large program, that is, a top-level program, then the upper-level program may invoke one of the data listed above in this Notepad.
So we call these multi-column functions as the interface for this notepad.
Then calling these interfaces is the public function (method) of this class through Notepad.
But how do you make a record? It is clear that the recorded string cannot be recorded in an array because the length of the array is pre-set. This is a generic class container arraylist<> , this Arraylist is also a class of the system, so when using it to define a new object to come out: private arraylist<string> Notes = new arraylist<string> (); also declare import java.util.ArrayList;
ArrayList can be arbitrarily stored in the data, unlimited number, which realizes the requirements of Notepad.
Basic operations for Arraylist: arraylist<string> notes
- Notes.add ()
- Notes.size ()
- Notes.remove (Index)
- Notes.get (Index)
- Notes.toarray (string[] a=new string[notes.size ()])
The interface function of Notepad is implemented by the above operation.
1 Packagenotebook;2 3 Importjava.util.ArrayList;4 5 Public classNotebook {6 7 PrivateArraylist<string> notes =NewArraylist<string>();8 9 Public voidAdd (String s) {Ten Notes.add (s); One } A - Public intGetSize () { - returnnotes.size (); the } - - Public voidRemovenote (intindex) { - Notes.remove (index); + } - + PublicString Getnote (intindex) { A returnNotes.get (index); at } - - Publicstring[] List () { -String[] A =Newstring[notes.size ()]; - Notes.toarray (a); - returnA; in } - to Public Static voidMain (string[] args) {//Test +Notebook NB =NewNotebook (); -Nb.add ("Frist"); theNb.add ("Second"); * System.out.println (Nb.getsize ()); $String[] A =nb.list ();Panax Notoginseng for(String s:a) { - System.out.println (s); the } + } A the}Notebook.java
Run:
Java Basic Learning--object container