范型容器类

123 阅读2分钟

「这是我参与11月更文挑战的第14天,活动详情查看:2021最后一次更文挑战」。

范型类

容器类:用来存放对象

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

容器类有两个类型:

  • 容器的类型(eg:ArrayList)
  • 元素的类型(eg:) ArrayList of String 使用:
notes.add(s);
//notes.add(10);这样写会出现错误,因为ArrayList of String,括号里只接受String

Size():通过调用Size()函数可知notes里面放了多少东西。

notes.size();

notes.toArray(a); 把数组填起来 还是昨天的代码,现在需要往里面填东西了。

package notebook;
import java.util.ArrayList;
public class NoteBook {

	private ArrayList<String> notes=new ArrayList<String>();
	//用来存放String的ArrayList。
	//这种类型叫做范型类,这种范型类是一种容器
	//notes是对象管理者
	public void add(String s) {
		notes.add(s);
	}
	public void add(String s, int location) {
		notes.add(location,s);
	}
	public int getSize() {
		return notes.size();
	}
	public String getNote(int index) {
		return notes.get(index);
	}
	public void removeNote(int index) {
		notes.remove(index);
	}
	public void list() {
		String[] a=new String[notes.size()];
//		for(int i=0;i<notes.size;i++) {
//			a[i]=notes.get(i);
//		}
		notes.toArray(a);
		//把数组填起来
		return a;
	}
	/*public String[] list() {
	
	}*/
	public static void main(String[] args) {
		NoteBook nb=new NoteBook();//做了个对象
		nb.add("first");
		nb.add("second");
		nb.add("third",1);
		System.out.println(nb.getSize());
		System.out.println(nb.getNote(0));
		System.out.println(nb.getNote(1));
		nb.removeNote(1);
		String[] a=nb.list();
		for(String s:a) {
			System.out.println(s);
		}
	}
}

ArrayList的操作:ArrayList的下标从0开始

对象数组

当数组的元素的类型是类的时候,数组的每一个元素其实只是对象的管理者而不是对象本身。因此,仅仅创建数组并没有创建其中的每一个对象!

集合容器(Set)

集合就是数学中的集合的概念:所有的元素都具有唯一的值,元素在其中没有顺序。

散列表(Hash)

传统意义上的Hash表,是能以int做值,将数据存放起来的数据结构。Java的Hash表可以以任何实现了hash()函数的类的对象做值来存放对象。

Hash表是非常有用的数据结构,熟悉它,充分使用它,往往能起到事半功倍的效果。