Directory:
ArrayList sequential generic container
HashSet collection container
HashMap
To use Java to implement the function of notepad. First, list the required functions of Notepad:
can add records (strings);
can get the number of records;
can delete one of the records;
can get the specified number of records;
can List all records.
If this notepad is part of a large program, that is to say, there is an upper-level program, then the upper-level program may call some of the data listed above in this notepad.
So we call the functions listed above the interface of this notepad.
Then calling these interfaces is through the public function (method) of the Notepad class.
But how to achieve recording? Obviously the recorded string cannot be recorded in an array, because the length of the array is preset. At this time, the generic container Arraylist will be used. This arraylist is also a class of the system, so when using it, a new object must be defined: private Arraylist
arraylist can store any data in it, with no limit on the number, which meets the requirements of Notepad.
Basic operations of arraylist: Arraylist
notes.add()
notes.size()
notes.remove(index)
notes.get(index)
notes.toArray(String[] a =new String[notes.size()])
Implement the interface function of Notepad through the above operations.
Run:
In addition, the container type also includes a collection container (Set), such as HashSet, which is also a class. Its characteristic is that the internal elements are not sorted and cannot have duplicate elements, which is the same as in mathematics. The collection concept is the same.
You can see the difference between the two containers ArrayList and HashSet from the program running results.
Note: You can also see from the program that the output of the two containers no longer assigns each element of the container to another array, and then outputs each element in the array through a for each loop. Here we directly println out a container object, which is fine. This is because: {
If a class has a "public String toString() {}" function, you can directly println the object name of this class, and the toString function will be automatically called when outputting , as shown in the second red box. Therefore, we guess that there must be functions similar to "public String toString() {}" in the two public class source files of ArrayList and HashSet.
}
--------------------------------------------- --------------------------------------------------
HashMap Container: HashMap
A key corresponds to a value. When a key is put multiple times, this key corresponds to the last put value, as shown in the figure: (A program that inputs the denomination and outputs the name of the U.S. dollar, such as: 1 cent is called 1penny . )