欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

ArrayList,

来源: javaer 分享于  点击 37038 次 点评:213

ArrayList,


ArrayList的使用

存储字符串并遍历

import java.util.ArrayList;
import java.util.Iterator;

/*
 * List的子类特点:
 *      ArrayList:
 *          底层数据结构是数组,查询快,增删慢
 *          线程不安全,效率高
 *      Vector:
 *          底层数据结构是数组,查询快,增删慢
 *          线程安全,效率低
 *      LinkedList:
 *          底层数据结构是链表,查询慢,增删快
 *          线程不安全,效率高
 * 
 * 案例:
 *      使用List的任何子类存储字符串或者存储自定义对象并遍历。
 * 
 * ArrayList的使用。    
 *      存储字符串并遍历
 */
public class ArrayListDemo {
    public static void main(String[] args) {
        // 创建集合对象
        ArrayList array = new ArrayList();

        // 创建元素对象,并添加元素
        array.add("hello");
        array.add("world");
        array.add("java");

        // 遍历
        Iterator it = array.iterator();
        while (it.hasNext()) {
            String s = (String) it.next();
            System.out.println(s);
        }

        System.out.println("-----------");

        for (int x = 0; x < array.size(); x++) {
            String s = (String) array.get(x);
            System.out.println(s);
        }
    }
}

ArrayList存储自定义对象并遍历

package com.arraylist;

import java.util.ArrayList;
import java.util.Iterator;
/*
 * ArrayList存储自定义对象并遍历
 */
public class ArrayListDemo02 {
    public static void main(String[] args) {
        ArrayList arr = new ArrayList();

        arr.add(new Student("qiwei", 22));
        arr.add(new Student("wangzhongmao", 25));
        arr.add(new Student("wuhuizhi", 24));
        arr.add(new Student("chenkai", 23));

        //迭代器遍历
        //Iterator<E> iterator():返回在此 collection 的元素上进行迭代的迭代器
        Iterator it = arr.iterator();
        //hasNext(),next()迭代器特有方法
        while (it.hasNext()) {
            // String s = (String) it.next();
            // java.lang.ClassCastException 类型转换出错
            //注意集合里存储的类型
            Student stu = (Student) it.next();
            //System.out.println(stu);
            System.out.println(stu.getName() + "---" + stu.getAge());
        }

        System.out.println("-------------");
        //for循环遍历
        for(int i = 0; i < arr.size(); i++) {
            Student stu = (Student) arr.get(i);
            System.out.println(stu.getName() + "---" + stu.getAge());
        }
    }
}

/**
 * 学生类
 *      属性:姓名,年龄
 *      方法:获取信息的方法
 * 
 */
class Student {
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }

}

相关文章

    暂无相关文章

用户点评