黑马程序员——集合(一)Collection ,List

——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——-
之前学到的数组可以算一个存储容器,可以用来存储基本数据类型,也可以用来存储引用数据类型,但是在存储引用数据类型是存在血多弊端,所以集合类的出现将会为存储引用数据类型带来许多方便。换句话说,集合类Collection的出现是为了更方便对象的存储。集合类存储对象的优势表现在:集合类可以用于存储数量不等的多个对象,还可用于保存具有映射关系的关联数组。

Colle接口继承树

从上图看出
Collection接口API可以分为以下几类。
Iterator迭代器接口
Collection子接口之一:Set接口
HashSet LinkedHashSet TreeSet
Collection子接口之二: List接口
ArrayList LinkedList Vector
Map接口
HashMap TreeMap Hashtable
Collections工具类
Collection的常见方法:
增:boolean add(object obj)
boolean addAll(Collection coll)
删:boolean remove(object obj)
boolean removeAll(Collection coll)
判断:boolean contains(object obj)
boolean containsAll(Collection coll)
boolean isEmpty();
获取:
int size();
Iterator iterator();
示例:

public class TestCollection {
    @Test
    public void testCollection3() {
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(new String("AA"));
        coll.add(new Date());
        coll.add("BB");
        coll.add(new Person("MM", 23));

        Collection coll1 = new ArrayList();
        coll1.add(123);
        coll1.add(new String("AA"));
        // 10.removeAll(Collection coll):从当前集合中删除包含在coll中的元素。
        coll.removeAll(coll1);
        System.out.println(coll);
        //11.equals(Object obj):判断集合中的所有元素是否完全相同
        Collection coll2 = new ArrayList();
        coll2.add(123);
        coll2.add(new String("AA1"));
        System.out.println(coll1.equals(coll2));
        //12.hashCode():
        System.out.println(coll.hashCode());
        System.out.println();
        //13.toArray() :将集合转化为数组
        Object[] obj = coll.toArray();
        for(int i = 0;i < obj.length;i++){
            System.out.println(obj[i]);
        }
        System.out.println();
        //14.iterator():返回一个Iterator接口实现类的对象,进而实现集合的遍历!
        Iterator iterator = coll.iterator();
        //方式一:不用
        /*System.out.println(iterator.next());
        System.out.println(iterator.next());
        System.out.println(iterator.next());*/
        //方式二:不用
//      for(int i = 0;i < coll.size();i++){
//          System.out.println(iterator.next());
//      }
        //方式三:使用
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

    @Test
    public void testCollection2() {
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(new String("AA"));
        coll.add(new Date());
        coll.add("BB");
        // Person p = new Person("MM",23);
        coll.add(new Person("MM", 23));
        System.out.println(coll);
        // 6.contains(Object obj):判断集合中是否包含指定的obj元素。如果包含,返回true,反之返回false
        // 判断的依据:根据元素所在的类的equals()方法进行判断
        // 明确:如果存入集合中的元素是自定义类的对象。要求:自定义类要重写equals()方法!
        boolean b1 = coll.contains(123);
        b1 = coll.contains(new String("AA"));
        System.out.println(b1);
        boolean b2 = coll.contains(new Person("MM", 23));
        System.out.println(b2);
        // 7.containsAll(Collection coll):判断当前集合中是否包含coll中所有的元素
        Collection coll1 = new ArrayList();
        coll1.add(123);
        coll1.add(new String("AA"));

        boolean b3 = coll.containsAll(coll1);
        System.out.println("#" + b3);
        coll1.add(456);
        // 8.retainAll(Collection coll):求当前集合与coll的共有的元素,返回给当前集合
        coll.retainAll(coll1);
        System.out.println(coll);
        // 9.remove(Object obj):删除集合中的obj元素。若删除成功,返回true。否则,返回false
        boolean b4 = coll.remove("BB");
        System.out.println(b4);

    }

    @Test
    public void testCollection1() {
        Collection coll = new ArrayList();
        // 1.size():返回集合中元素的个数
        System.out.println(coll.size());
        // 2.add(Object obj):向集合中添加一个元素
        coll.add(123);
        coll.add("AA");
        coll.add(new Date());
        coll.add("BB");
        System.out.println(coll.size());
        // 3.addAll(Collection coll):将形参coll中包含的所有元素添加到当前集合中
        Collection coll1 = Arrays.asList(1, 2, 3);
        coll.addAll(coll1);
        System.out.println(coll.size());
        // 查看集合元素
        System.out.println(coll);
        // 4.isEmpty():判断集合是否为空
        System.out.println(coll.isEmpty());
        // 5.clear():清空集合元素
        coll.clear();
        System.out.println(coll.isEmpty());
    }
}

Java 集合可分为 Collection 和 Map 两种体系
Collection接口:
Set:元素无序、不可重复的集合 —类似高中的“集合”
List:元素有序,可重复的集合 —”动态”数组
Map接口:具有映射关系“key-value对”的集合

List集合类中元素有序、且可重复,集合中的每个元素都有其对应的顺序索引。所以提那家进List中的对象一定要冲下equals()方法。
List容器中的元素都对应一个整数型的序号记载其在容器中的位置,可以根据序号存取容器中的元素。
List特有的方法(能操作角标的方法)
List中相对于Collection,新增加的方法
void add(int index, Object ele):在指定的索引位置index添加元素ele
boolean addAll(int index, Collection eles)
Object get(int index):获取指定索引的元素
Object remove(int index):删除指定索引位置的元素
Object set(int index, Object ele):设置指定索引位置的元素为ele
int indexOf(Object obj):返回obj在集合中首次出现的位置。没有的话,返回-1
int lastIndexOf(Object obj):返回obj在集合中最后一次出现的位置.没有的话,返回-1
List subList(int fromIndex, int toIndex):返回从fromIndex到toIndex结束的左闭右开一个子list
示例:

public void testList2(){
        List list = new ArrayList();
        //添加各种类型的元素
        list.add(123);
        list.add(456);
        list.add(new String("AA"));
        list.add(new String("GG"));
        list.add(456);
        System.out.println(list.indexOf(456));
        System.out.println(list.lastIndexOf(456));
        System.out.println(list.indexOf(123) == list.lastIndexOf(123));
        System.out.println(list.indexOf(444));

        List list1 = list.subList(0, 3);
        System.out.println(list1);
    }
    public void testList1(){
        List list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add(new String("AA"));
        list.add(new String("GG"));
        System.out.println(list);
        list.add(0,555);
        System.out.println(list);
        Object obj = list.get(1);
        System.out.println(obj);
        list.remove(0);
        System.out.println(list.get(0));
        list.set(0, 111);
        System.out.println(list.get(0));
    }
}

遍历list的方法:
①迭代器iterator
②高级for循环
③一般for循环
示例:

public class TestList {
    @Test
    public void testList(){
//      ArrayList list = new ArrayList();
        LinkedList list = new LinkedList();
        list.add(123);
        list.add(456);
        list.add("AA");
        list.add("BB");
        //get(int index)
        //set(int index,Object obj)
        list.set(1, 111);
        //add(int index,Object obj)
        list.add(2, "MM");
        //remove(int index)
        list.remove(0);
        System.out.println(list.get(0));
        System.out.println();
        //遍历集合元素:方式一
        Iterator iterator = list.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
        System.out.println();
        //增强for循环
        for(Object o : list){
            System.out.println(o);
        }
        System.out.println();
        //一般的for循环
        for(int i = 0;i < list.size();i++){
            System.out.println(list.get(i));
        }

    }
}

注意:在使用迭代时,不能通过集合对象操作集合中的元素,因为会发生并发修改异常,所以在迭代器时,只能用迭代器的方法操作元素。

List 额外提供了一个 listIterator() 方法,该方法返回一个 ListIterator 对象, ListIterator 接口继承了 Iterator 接口,提供了专门操作 List 的方法:
void add()

boolean hasPrevious()
Object previous()

Boolean hasNext()
Object next()

Iterator和ListIterator主要区别
一、ListIterator和Iterator都有hasNext()和next()方法,可以实现顺序向后遍历。但是ListIterator有hasPrevious()和previous()方法,可以实现逆向(顺序向前)遍历。Iterator就不可以。
二、ListIterator可以定位当前的索引位置,nextIndex()和previousIndex()可以实现。Iterator 没有此功能。
三、ListIterator有add()方法,可以向List中插入对象,而Iterator不能。
四、都可实现删除对象,但是ListIterator可以实现对象的修改,set()方法可以实现。Iterator仅能遍历,不能修改。因为ListIterator的这些功能,可以实现对LinkedList等List数据结构的操作。

List:
|–Vector:内部是数组数据结构,是同步的。增删,查询都很慢。
|–ArrayList:内部是数组数据结构,是不同步的,替代了Vector。替代了Vector,查询的速度快。
|–LinkedList:内部是链表数据结构,是不增删元素速度快。

使用LinkedList实现一个堆栈先进先出:
代码:

public class DuiZhan {
    private LinkedList linklist;//私有一个linkedlist

    DuiZhan(){
        linklist=new LinkedList();
    }

    public void myAdd(Object obj){//实现添加方法
        linklist.addFirst(obj);

    }

    public Object myGet(){//获取元素
        return linklist.removeLast();
        //return linklist.removeFirst();
    }

    public boolean isNull(){//判断是否为空
       return linklist.isEmpty();
    }

    void printDz(){
        System.out.println(linklist);
        }

    }
public class DuizhanDemo {
    public static void main(String[] args){
      DuiZhan dz=new DuiZhan();

        System.out.println(dz.isNull());

        dz.myAdd("123");
        dz.myAdd(0x3c);
        dz.myAdd(789);
        dz.myAdd(126);

        System.out.println(dz.isNull());
        dz.printDz();
        System.out.println(dz.myGet());
        System.out.println(dz.myGet());
        System.out.println(dz.myGet());
        System.out.println(dz.myGet());
        dz.printDz();
        System.out.println(dz.isNull());
    }
}

ArrayList示例
向ArrayList里面存入,Person对象。姓名和年龄相同为同一对象,去除相同的对象
代码:

public class Person {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public boolean equals(Object obj) {//判断两队想是否相等
        if (!(obj instanceof Person))
            return false;

            Person p= (Person) obj;
        System.out.println(this.name+"~~~"+p.name);
        return this.name.equals(p.name)&&this.age==p.age;
    }
}
public class ArrayPerson {
    public static void main(String[] args){
        ArrayList ap=new ArrayList();
        ap.add(new Person("lee1",10));
        ap.add(new Person("lee2",10));
        ap.add(new Person("lee3",10));
        ap.add(new Person("lee2",10));
        printAP(ap);
        ap= quChong(ap);
        printAP(ap);
    }
    public static void printAP(ArrayList al){
        for (Iterator it=al.iterator();it.hasNext();){
            Person p= (Person) it.next();
            System.out.println(p.getName()+"--"+p.getAge());
        }
        System.out.println();

    }
    public static ArrayList quChong(ArrayList al){
        ArrayList newal= new ArrayList();

        for (Iterator it=al.iterator();it.hasNext();){
           Object obj= it.next();
            if (!(newal.contains(obj)))
                newal.add(obj);
        }
        return newal;
    }

}

此文介绍了Collection和List的常用方法和示例。
——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——-

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值