Java类集框架(二):List子接口

List子接口最大的功能是里面保存的数据可以存在重复的内容。List接口在对Collection接口扩充的方法如下:
- public E get(int index):普通,取得索引编号的内容
- public E set(int index, E element):普通,修改指定索引编号的内容
- public ListIterator<E> listIterator():普通,为ListIterator接口实例化

在使用List接口时可以利用ArrayLis或Vector两个子类来进行接口对象的实例化操作。


ArrayList

简单操作示例

  • List基本操作
import java.util.ArrayList;
import java.util.List;

/**
 * List基本操作,包括添加元素、获取容量、判断是否为空以及循环输出List内容。
 * @author seeker
 *
 */
public class TestArrayList {

    public static void main(String[] args) {
        // 应用泛型保证集合中的所有数据类型都一致
        List<String> all = new ArrayList<>();
        System.out.println("长度: " + all.size() + ",是否为空:" + all.isEmpty());
        all.add("Hello");
        all.add("World");
        all.add("Hello");
        System.out.println("长度: " + all.size() + ",是否为空:" + all.isEmpty());
        for(int i = 0;i < all.size();i++) {
            String str = all.get(i);
            System.out.println(str);
        }
    }
}
  • 在集合中保存对象
public class Book {

    private String title;
    private double price;

    public Book(String title, double price) {
        this.setTitle(title);
        this.setPrice(price);
    }
    // 省略getter、setter方法
    // 必须覆写equals()方法,才能调用Collection接口中的remove()或contains()方法
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof Book))
            return false;
        Book book = (Book) obj;
        if (this.title.equals(book.title) && this.price == book.price)
            return true;
        return false;
    }

    @Override
    public String toString() {
        return this.title + "--->>" + this.price;
    }

}

import java.util.ArrayList;
import java.util.List;

public class SaveObject {

    public static void main(String[] args) {
        List<Book> all = new ArrayList<>();
        Book book1 = new Book("Gone with the wind",24.99);
        Book book2 = new Book("Harry Potter", 23.88);
        all.add(book1);
        all.add(book2);
        System.out.println(all.contains(book1)); //判断book1是否在all中
        all.remove(book1);                       //从all中删除book1
        System.out.println(all);
    }
}

Array与ArrayList的区别

  • Array中保存的内容时固定的,ArrayList中保存的内容是可变的。
  • Array中可以保存任何数据类型的元素,ArrayList只能保存引用类型,而不能保存基本数据类型的元素。
  • Array效率相对高一些,进行数据保存与取得时,ArrayList需要进行一系列的判断,而Array只需要操作索引。

旧的子类:Vector

Vector类的基本操作方法与ArrayList类相似。最大的区别在于Vector类中的部分方法使用synchronized关键字声明,即采用了同步操作,具备线程安全的特性。

猜你喜欢

转载自blog.csdn.net/MeowingCat/article/details/80151065