List子接口保存数据最大特点是可以重复数据的保存。List子接口针对Collection子接口进行了大量方法扩充。
public E get(int index) 根据索引取得制定的元素内容(框架中100%用到)
public E set(int index, E element) 修改制定索引元素的内容
public ListIterator<E> listIterator 为ListIterator接口实例化
List本身属于一个接口,如果想取得接口的实例化对象,那么应该通过子类实例完成,那么List子类下有两个常用子类:ArrayList、Vector
新的子类:ArrayList
只要使用了List接口,首选ArrayList子类
范例:List基本使用
import java.util.ArrayList; import java.util.List; public class Hello{ public static void main(String[] args) throws Exception { List<String> all = new ArrayList<String>(); System.out.println(all.isEmpty());//是否为空 all.add("Hello"); all.add("Hello"); all.add("Hello"); //重复元素 System.out.println(all.isEmpty());//是否为空 System.out.println(all); //输出结果为:[Hello, Hello, Hello] System.out.println("数据个数:" + all.size()); } }
既然要进行集合的数据输出,不可能直接输出一个接口对象,那么采用循环的方式完成输出
利用size()方法控制循环次数,利用get()方法取出内容。
范例:输出集合数据
import java.util.ArrayList; import java.util.List; public class Hello{ public static void main(String[] args) throws Exception { List<String> all = new ArrayList<String>(); all.add("Hello1"); all.add("Hello2"); all.add("Hello3"); for(int x = 0; x < all.size();x++) { String str = all.get(x); System.out.println(str); } } }
如果以上操作不使用List而用Collection接口接收,那么在于get()方法问题了,因为是由list方法定义的
在List接口有提供contains()、remove()的操作方法。这两个方法都需要子方法的支持
范例:保存自定义类的对象
import java.util.ArrayList; import java.util.List; class Dept{ private int deptno; private String dname ; private String loc; public Dept(int deptno, String dname, String loc) { super(); this.deptno = deptno; this.dname = dname; this.loc = loc; } @Override public String toString() { return "Dept [deptno=" + deptno + ", dname=" + dname + ", loc=" + loc + "]"; } @Override public boolean equals(Object obj) { if(this == obj) { return true; } if(obj == null) { return false; } if(!(obj instanceof Dept)) { return false; } Dept dept = (Dept) obj; return this.deptno == dept.deptno && this.dname.equals(this.dname)&&this.loc.equals(dept.loc); } } public class Hello{ public static void main(String[] args) throws Exception { List<Dept> all = new ArrayList<Dept>(); all.add(new Dept(10, "adsf", "jrt")); all.add(new Dept(20, "ads45f", "jasrt")); all.add(new Dept(130, "adssf", "jrvat")); all.remove(new Dept(130, "adssf", "jrvat"));//删除数据 for (int x = 0; x < all.size();x++) { System.out.println(all.get(x)); } } }
整个过程的使用和自定义的链表完全一样的