Java基础学习总结--对象容器

时间:2023-11-25 10:56:38

目录:

要用Java实现记事本的功能。首先列出记事本所需功能:

  1. 可以添加记录(字符串);
  2. 可以获得记录条数;
  3. 可以删除其中某一条记录;
  4. 可以获得指定第几条的记录;
  5. 可以列出所有的记录。

如果这个记事本是某个大程序的其中一部分,也就是说还有上层程序,那么上层程序就有可能会调用这个记事本以上列出的某个数据。

所以我们称上述所列功能为这个记事本的 接口

那么调用这些接口就是通过记事本这个类的public函数(method)。

但是,怎么实现记录呢?显然所记录的字符串不能记录在某个数组里,因为数组的长度是预先设定好的。这时就要用到 泛型容器 Arraylist<> ,这个arraylist也是系统的一个类,所以在使用它的时候要定义一个新的对象出来:private Arraylist<String> notes = new Arraylist<String>();  还要声明 import java.util.ArrayList;

arraylist可以任意往里面存放数据,不限数目,这就实现了记事本的要求。

arraylist的基本操作: Arraylist<String> notes

  • notes.add()
  • notes.size()
  • notes.remove(index)
  • notes.get(index)
  • notes.toArray(String[] a=new String[notes.size()])

通过以上操作实现记事本的接口函数。

 package notebook;

 import java.util.ArrayList;

 public class Notebook {

     private ArrayList<String> notes = new ArrayList<String>();

     public void add(String s) {
notes.add(s);
} public int getSize() {
return notes.size();
} public void removeNote(int index) {
notes.remove(index);
} public String getNote(int index) {
return notes.get(index);
} public String[] list() {
String[] a = new String[notes.size()];
notes.toArray(a);
return a;
} public static void main(String[] args) { //test
Notebook nb = new Notebook();
nb.add("frist");
nb.add("second");
System.out.println(nb.getSize());
String[] a = nb.list();
for(String s:a) {
System.out.println(s);
}
} }

Notebook.java

运行:

Java基础学习总结--对象容器

-----------------------------------------------------------------------------------------

另外,容器类型还有集合容器(Set),如HashSet,同样是一个类,所具有的特性是内部元素是不排序的,不能有重复的元素,与数学里的集合概念相同。

Java基础学习总结--对象容器

由程序运行结果可以看到ArrayList 和HashSet 这两种容器的不同。

注意:由程序还可以看到,两个容器的输出不再是把容器的每个元素赋值给另一个数组,再通过for each循环把数组里的每个元素输出。在这里我们是直接println出来了一个容器的对象,是可以的。这是因为:{

             如第一个红框所示,如果一个类里有“public String toString() {}”函数,则可以直接println这个类的对象名,输出的时候会自动调用toString函数的,如第二个红框所示。所以,我们猜测,ArrayList和HashSet这两个公共类源文件里一定也有“public String toString() {}” 类似的函数

             }

-----------------------------------------------------------------------------------------

HashMap容器: HashMap<Key,Value>


一个键对应一个值,当给一个键多次put之后,这个键对应最后put的值,如图:(一个输入面额,输出多对应美元名称的程序,如:1美分叫做1penny。)

Java基础学习总结--对象容器

HashMap的遍历:

Java基础学习总结--对象容器

Java基础学习总结--对象容器