Java进阶:集合框架1

一.集合类

1.概述

面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,Java就提供了集合类。

集合类的特点:

集合只用于存储对象,集合的长度是可变的

集合可以储存不同的类型对象(因为集合实现了泛型)

//参数化类型

//集合可以存储不同类型的对象

ArrayList<Integer> arrayList=new ArrayList<>();

ArrayList<String> a=new ArrayList<>();

ArrayList<A> b=new ArrayList<>();

集合和数组的区别:

数组也可以存储对象,但长度是固定的;集合长度是可变的

数组中可以存储基本数据类型,集合只能存储对象,也就是引用数据类型

集合的适用范围更广,对于基本的数据类型也有自动装箱和拆箱机制

ArrayList<Integer>arrayList=new ArrayList<>();

//通过装箱将基本数据类型放入集合中

arrayList.add(1);

2.集合类的框架

Collection接口常用的子接口有:List接口、Set接口

List列表接口常用的实现类有ArrayList数组类、LinkedList链表类

Set集合接口常用的实现类有HashSet类、TreeSet类

Collection基本操作:增删改查

List:元素有序、元素可重复、有索引

ArrayList:顺序表、用数组实现、线程安全

LinkedList:链表、双向链表实现、非线程安全

vetor:向量、数组实现、线程安全

Set:元素无序,元素不可重复,没有索引

HashSet:哈希表实现

TreeSet:红黑树实现

3.参数化类型和泛型

泛型用来指明集合中存储数据的类型<数据类型>,参数化类型用来具体数据类型,类似形参和实参的关系

为什么要有参数化类型?

保证从语法层面,强制只能向一个集合中,放入一种具体类型的数据

二.Collection接口

jdk中的描述:

Colletion层次结构中的根结构。Collection表示一组对象,这些对象也成为Collection的元素。

一些Collection允许有重复的元素,而另一些不允许。一些Collection是有序的,而另一些是无序的。

JDK不提供此接口的任何直接实现:它提供更具体的子接口(如Set和List)实现

三.集合Collection的方法

Java中三种长度表现形式:

数组.length属性返回值int

字符串.length方法返回值int

集合.size()方法返回值int

集合Collection的方法是实现类必须拥有的方法

1.第一类:针对单个元素的操作

boolean add(E e):将元素追加到当前元素集合的末尾,添加成功返回true

Object[ ] toArray():将集合中的元素,转成一个数组中的元素,集合转成数组。返回一个存储对象的数组

集合对象中,已经覆盖了Object的toString方法,所以可以直接打印集合中的元素值

boolean contains(Object o):判断对象是否存在于集合中,对象存在返回true

void clear():清空集合中的所有元素,集合容器本身依然存在

boolean remove(Object o):

移除集合中指定的元素,删除成功返回true

当删除不存在的元素时,返回false

当集合中有重复元素时,只会删除第一个

boolean contains(Object o):判断当前集合中是否包含指定的元素,是则返回true

boolean isEmpty():判断集合是否为空

private static void function(){ 
    //接口多态调用
    Collection coll = new ArrayList(); 
    coll.isEmpty();
    coll.add("abc");
    coll.add("money");
    coll.add("itcast");
    coll.add("itheima");
    coll.add("money");
    coll.add("123");

    boolean b = coll.remove("money");
    boolean b = coll.contains("itcast");
    System.out.println(a.contains("lisi")); //返回false
    coll.clear();
}

2.第二类:针对集合的操作(一次操作多个元素)

boolean addAll(Collection c):将指定的collection中的所有元素都添加到此collection中

boolean removeAll(Collection c):移除此collection中那些包含在指定collection中的所有元素

boolean containsAll(Collection c):如果此collection中包含指定collection中的全部元素,则返回true

boolean retainAll(Collection c):仅保留此collection中那些包含在指定collection的元素。如果此collection由于调用而发生改变,则返回true,否则返回false

public class CollectionDemo{

        public static void main(String[] args){

        //创建第一个集合对象

        Collection<String> a=new ArrayList<>();

        a.add("zs");

        a.add("lisi");

        a.add("wangwu");

        //创建第二个集合对象

        Collection<String> b=new ArrayList<>();

        b.add("zs");

        b.add("lisi");

        b.add("wangwu");

        //boolean addAll(Collection c)
        //boolean result = a.addAll(b);
        //System.out.println(result);
        //b集合中的元素,复制了一份全部添加到a集合中
        //System.out.println(a);
        //b集合本身没有任何变化
        //System.out.println(b);

        //boolean removeAll(Collection c)
        // a.removeAll(b);
        // System.out.println(a);

        //boolean containsAll(Collection c)
        //System.out.println(a.containsAll(b));


        //boolean retainAll(Collection c)

        System.out.println(

a.retainAll(b)

);

        System.out.println(

a

);

        System.out.println(

b

);

        }

}

三.集合元素的遍历

1.第一种遍历方式:将集合转化为数组

public class CollectionDemo{

        public static void main(String[] args){

        //第一步得到集合对象

        Collection<String> a=new ArrayList();

        Collection<Integer>b=new ArrayList();

        a.add("zs");

         a.add("lisi");

         a.add("wangwu");

        a.add("zhaoliu");

        Object[ ] objects = a.toArray(a);

        for(int i=0;i<objects.length;i++){

                System.out.print(objects[i]+" ");

        }

        System.out.println();

        }

}

2.第二种遍历方式:通过迭代器遍历集合中的所有元素(集合专用)

四. Iterator接口(迭代器)

1.迭代器概述

collection集合元素的通用获取方式:在取元素之前先要判断集合中是否有元素,如果有就取出该元素,继续进行判断,直到取出全部元素,称为迭代。

每种集合的底层数据结构不同,但是判断以及取出的动作相同,Java提供了一个迭代器定义了统一的判断元素和取元素的方法。

Collection接口定义的iterator() 方法 用来返回基于当前数据集合的迭代器对象。

Iterator为什么不是类而是定义为一个接口?

由于一旦把针对不同具体集合的生成迭代器的方法,放在一个类中,通常各个不同迭代器的方法,可能会有一些公共方法,被抽象成一个方法,定义成一个万能类的话会很难维护。

迭代器的优点:

每一个具体实现类都实现了Iterator接口,能够返回一个针对自己的存储结构的具体的Iterator接口的实现子类。

Iterator向上层的使用者,屏蔽了具体的底层集合类的实现细节,使用方法一样

2.Iterator接口的抽象方法

boolean hasNext():判断是否还有元素,有则返回true

next():取出集合中的下一个元素

remove():删除集合中当前访问的元素

3.遍历的代码实现

/*
原理:
Collection接口定义方法 Iterator iterator()
ArrayList 重写方法 iterator(),返回了Iterator接口的实现类的对象
使用 ArrayList 集合的对象Iterator it = array.iterator(),运行结果就是Iterator接口的实现类的对象
it是接口的实现类对象,调用方法 hasNext 和 next 来实现集合元素迭代
*/
public class CollecitonDemo {
    public static void main(String[] args) {

        //第一步,得到一个集合对象
        Collection<String> a = new ArrayList();
        Collection<Integer> b = new ArrayList();

        a.add("zs");
        a.add("lisi");
        a.add("wangwu");
        a.add("zhaoliu");

        //集合类专用的遍历方式  通过迭代器遍历集合中的所有元素
        //调用集合的方法iterator()获取出 Iterator接口的实现类的对象
        Iterator<String> iterator = a.iterator();

        //利用迭代器遍历
        //迭代是反复内容,使用循环实现,循环的条件,集合中没元素, hasNext()返回了false
        //调用方法hasNext()判断集合中是否有元素
        while(iterator.hasNext()) {
            //调用方法next()取出集合中的元素
            System.out.println(iterator.next());
        }
        //for循环迭代写法:
//        for (Iterator<String> it2 = coll.iterator(); //it2.hasNext();  ) {
//         System.out.println(it2.next());
//       }

        //利用迭代器删除集合中的元素
        //注意要执行,要把前面的注释掉,因为size已经在最后了
        //迭代是反复内容,使用循环实现,循环的条件是集合中没元素, hasNext()返回了false
        while(iterator.hasNext()) {
            String s = iterator.next();
            //if(1 == i)  和 if(i == 1)
            if("wangwu".equals(s)) {
            //从Collection中删除当前访问到的元素
            iterator.remove();
            }
        }
        System.out.println(a);

        Collection<String> list = new LinkedList<>();
        list.add("stu1");
        list.add("stu2");
        list.add("stu3");
        list.add("stu4");

        //利用迭代器,遍历LinkedList
        Iterator<String> iterator1 = list.iterator();

        while(iterator1.hasNext()) {
            System.out.println(iterator1.next());
        }
    }
}

4.实现原理

while(it.hasNext()) {
    System.out.println(it.next());
}
//cursor记录的索引值不等于集合的长度返回true,否则返回false
public boolean hasNext() {
   return cursor != size; //cursor初值为0
}
//next()方法作用:
//返回cursor指向的当前元素
//cursor++
public Object next() {
    int i = cursor;
    cursor = i + 1;
    return  elementData[lastRet = i];
}

5.例题:存储自定义对象并遍历,Student(name,age)

public class Student {
    //成员属性
    private String name;
    private int age;
    //构造方法
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    //get和set方法
    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;
    }
    //重写toString(),实现输出对象
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
public class IteratorExercise {
    public static void main(String[] args) {

        //初始化一个存放Student类对象的集合对象
        Collection<Student> a = new ArrayList<>();

        a.add(new Student("zs", 24));
        a.add(new Student("lisi", 25));
        a.add(new Student("wangwu", 26));
        //System.out.println(a);


        //完成遍历
        Iterator<Student> iterator = a.iterator();

        while(iterator.hasNext()) {
            Student stu = iterator.next();
            System.out.println(stu.getName() + " -- " + stu.getAge());

            //以下做法是错误的,因为每调用一次next()方法
            //cursor都会后移一位,就指向了下一个对象元素
            //System.out.print(iterator.next().getName() + " -- " + iterator.next().getAge());
        }
    }
}

6. 集合迭代中的转型

  • 在使用集合时,我们需要注意以下几点:
  • 集合中存储其实都是对象的地址。
  • 存储时类型提升为 Object类型。取出时若要使用元素的特有内容,必须向下转型
//不指定存储的数据类,什么都存,就是 Object类型
Collection coll = new ArrayList(); 
coll.add("abc");
coll.add("aabbcc");
coll.add("shitcast");

//获取迭代器,也不能加<>
Iterator it = coll.iterator();
//由于元素被存放进集合后全部被提升为Object类型
//当需要使用子类对象特有方法时,需要向下转型
while (it.hasNext()) {
    String str = (String) it.next(); //获取的是Object类型
    System.out.println(str.length());
}
//注意:如果集合中存放的是多个对象,这时进行向下转型会发生类型转换异常。

五、增强for循环

1. 格式

//格式:
for( 数据类型  变量名 : 数组或者集合 ){
    System.out.println(变量);
}

2. 遍历数组

  • 好处: 代码少了,方便对容器遍历
  • 弊端: 没有索引,不能操作容器里面的元素
  • for 对于对象数组遍历的时候,可以调用对象的方法
  • 注意:增强 for 要遍历的集合,要判断是否为 null
public static void function(){
    int[] arr = {3,1,9,0};
    for(int i : arr){
        System.out.print(i+1+" ");
    }
    System.out.println(arr[0]); //输出 3
    //输出:4 2 10 1

    //遍历的时候,可以调用对象的方法
    String[] str = {"abc","itcast","cn"};
    for(String s : str){
        System.out.println(s.length());
    }
}

3. 遍历集合,存储自定义 Person 类型

public static void function(){
    ArrayList<Person> array = new ArrayList<Person>();
    array.add(new Person("a",20));
    array.add(new Person("b",10));
    for(Person p : array){
        System.out.println(p);// System.out.println(p.toString());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值