快捷搜索:

浅学 JAVA 集合

集合 分为Collections和Map 这两个接口下面有很多实现类 例如ArrayList HashMap.....

区别:Collections中的数据是一对一的关系

Map是以key和value,即键值对的方式存储数据

下面先学习迭代器 Iterator

迭代器的实现原理 :通过指针的移动 一个一个地把集合中的元素取出来

import java.util.ArrayList;
import java.util.Iterator;
public class Iterator_ {
    public static void main(String[] args) {
        ArrayList arr=new ArrayList();
        Book b1=new Book("西游记","吴承恩",20);
        Book b2=new Book("红楼梦","曹雪芹",25);
        Book b3=new Book("三国演义","罗贯中",30);
        arr.add(b1);
        arr.add(b2);
        arr.add(b3);
        //得到对应集合的迭代器
        Iterator iterator= arr.iterator();
        int num=0;
        while(iterator.hasNext()){
            Object book=iterator.next();
            System.out.println(++num+"."+book);
        }
    }
}
class Book{
    private String name;
    private String author;
    private int price;
    public String getName() {
        return name;
    }    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    public Book(String name, String author, int price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }
    @Override
    public String toString() {
        return "{" +
                "name=" + name +  +
                ", author=" + author +  +
                ", price=" + price +
                };
    }
}
经验分享 程序员 微信小程序 职场和发展