java 集合②

List实现类

ArrayList[重点]

数组结构实现,查询快、增删慢;

jdk1.2版本,版本效率快,线程不安全;

Vector

数组结构实现,查询快、增删慢

jdk1.0版本,运行效率慢,线程安全;

LinkedList

链表结构实现,增删快,查询慢。

实例ArrayList

package com.zhou.study.Arrary;

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

/**
 * ArrayList使用
 * 存储结构,数组,查找,遍历快,增删稍微慢点
 * @author:Zhou_jx,
 */
public class demo05 {
    public static void main(String[] args) {
        //创建集合
        ArrayList arrayList = new ArrayList();
        //添加元素
        Student s1 = new Student("刘德华",21);
        Student s2 = new Student("郭富城",22);
        Student s3 = new Student("梁朝伟",22);
        arrayList.add(s1);
        arrayList.add(s2);
        arrayList.add(s3);
        arrayList.add(s3);
        System.out.println("元素个数为:"+arrayList.size());
        System.out.println(arrayList.toString());
        //删除元素
        /*arrayList.remove(s1);*/
        arrayList.remove(new Student("刘德华",21));
        System.out.println("删除之后集合为:"+arrayList.toString());
        //遍历元素
        //迭代器
        Iterator it = arrayList.iterator();
        System.out.println("-----使用迭代器--------");
        while (it.hasNext()){
            Student s = (Student)it.next();
            System.out.println(s.toString());
        }
        //列表迭代器
        ListIterator ls = arrayList.listIterator();
        System.out.println("--------使用列表迭代器--------");
        while (ls.hasNext()){
            Student s = (Student)ls.next();
            System.out.println(s.toString());
        }

        System.out.println("--------使用列表迭代器反序--------");
        while (ls.hasPrevious()){
            Student s = (Student)ls.previous();
            System.out.println(s.toString());
        }
        //判断
        System.out.println(arrayList.contains(s2));
        System.out.println(arrayList.contains(s1));
        System.out.println(arrayList.isEmpty());
    }
}

其中实体类student中需要自己重写equals方法,这样自己进行remove删除时 arrayList.remove(new Student(“刘德华”,21));

因为remove时继承了object,而其中的equals方法不能满足自己的判定要求,从而进行改写

让其能够找到自己实体类中的对象

改写equals方法:

@Override
    public boolean equals(Object o) {
        //如果时用一个对象可以直接返回true
        if (this == o) return true;
        //判断对象是否为空
        if (o == null || getClass() != o.getClass()) return false;
        //判断是否时Student实体类类型
        if(o instanceof Student){
            Student s =  (Student)o;
            //比较属性
            if(this.name.equals(s.getName())&&this.getAge()==s.getAge()){
                return true;
            }
        }
        //都不满足,返回错误
        return false;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值