Java---->集合(上)

一、集合的框架


 
 1.集合、数组都是对多个数据进行存储操作的结构,简称Java容器。
 *   说明;此时的存储,主要是指能存层面的存储,不涉及到持久化的存储(.txt,.jpg,.avi,数据库中)

2.1数组在存储多个数据封面的特点:
 *      》一旦初始化以后,它的长度就确定了。
 *      》数组一旦定义好,它的数据类型也就确定了。我们就只能操作指定类型的数据了。
 *      比如:String[] arr;int[] str;
2.2数组在存储多个数据方面的特点:
 *      》一旦初始化以后,其长度就不可修改。
 *      》数组中提供的方法非常有限,对于添加、删除、插入数据等操作,非常不便,同时效率不高。
 *      》获取数组中实际元素的个数的需求,数组没有现成的属性或方法可用
 *      》数组存储数据的特点:有序、可重复。对于无序、不可重复的需求,不能满足。

 

 

二、集合框架涉及到的API


Java 集合可分为Collection和Map两种体系

Collection接口:单列数据,定义了存取一组对象的方法的集合
List:元素有序、可重复的集合
Set:元素无序、不可重复的集合
Map接口:双列数据,保存具有映射关系“key-value对”的集合
 

 

集合框架


 *      &---Collection接口:单列集合,用来存储一个一个的对象
 *          &---List接口:存储有序的、可重复的数据。  -->“动态”数组
 *              &---ArrayList、LinkedList、Vector
 *
 *          &---Set接口:存储无序的、不可重复的数据   -->高中讲的“集合”
 *              &---HashSet、LinkedHashSet、TreeSet
 *
 *      &---Map接口:双列集合,用来存储一对(key - value)一对的数据   -->高中函数:y = f(x)
 *          &---HashMap、LinkedHashMap、TreeMap、Hashtable、Properties
 

Collection接口方法


Collection 接口是List、Set 和Queue 接口的父接口,该接口里定义的方法既可用于操作Set 集合,也可用于操作List 和Queue 集合。
JDK不提供此接口的任何直接实现,而是提供更具体的子接口(如:Set和List)实现。
在Java5 之前,Java 集合会丢失容器中所有对象的数据类型,把所有对象都当成Object 类型处理;从JDK 5.0 增加了泛型以后,Java 集合可以记住容器中对象的数据类型。


Collection接口中的常用方法1


添加
add(Objec tobj)
addAll(Collection coll)
获取有效元素的个数
int size()
清空集合
void clear()
是否是空集合
boolean isEmpty()
是否包含某个元素
boolean contains(Object obj):是通过元素的equals方法来判断是否是同一个对象
boolean containsAll(Collection c):也是调用元素的equals方法来比较的。拿两个集合的元素挨个比较。
删除
boolean remove(Object obj) :通过元素的equals方法判断是否是要删除的那个元素。只会删除找到的第一个元素
boolean removeAll(Collection coll):取当前集合的差集
取两个集合的交集
boolean retainAll(Collection c):把交集的结果存在当前集合中,不影响c
集合是否相等
boolean equals(Object obj)
转成对象数组
Object[] toArray()
获取集合对象的哈希值
hashCode()
遍历
iterator():返回迭代器对象,用于集合遍历

package doy1;

/**
 * @author shkstart
 * @create 2021-10-31 15:08
 */
import org.junit.Test;

import java.util.*;

/**
 *
 * 三、Collection接口中的方法的使用
 *
 */
public class CollectionTest {

    @Test
    public void test1(){
        Collection coll = new ArrayList();

        //add(Object e):将元素e添加到集合coll中
        coll.add("AA");
        coll.add("BB");
        coll.add(123);  //自动装箱
        coll.add(new Date());

        //size():获取添加的元素的个数
        System.out.println(coll.size());    //4

        //addAll(Collection coll1):将coll1集合中的元素添加到当前的集合中
        Collection coll1 = new ArrayList();
        coll1.add(456);
        coll1.add("CC");
        coll.addAll(coll1);

        System.out.println(coll.size());    //6
        System.out.println(coll);

        //clear():清空集合元素
        coll.clear();

        //isEmpty():判断当前集合是否为空
        //isEmoty--->内部其实调用了equals()方法
        System.out.println(coll.isEmpty());
    }
    /**
     * Collection接口中声明的方法的测试
     *
     * 结论:
     * 向Collection接口的实现类的对象中添加数据obj时,要求obj所在类要重写equals().
     */
    @Test
    public void test(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add("cc");

//        Person p = new Person("Jerry",20);
//        coll.add(p);
        coll.add(new Person("Jerry",20));

        coll.add(new String("Tom"));
        coll.add(false);

        //1.contains(Object obj):判断当前集合中是否包含obj
        //我们在判断时会调用obj对象所在类的equals()。
        boolean contains = coll.contains(123);
        System.out.println(contains);
        System.out.println(coll.contains(new String("Tam")));
//        System.out.println(coll.contains(p));//true
        System.out.println(coll.contains(new Person("Jerry",20)));//false -->true

        //2.containsAll(Collection coll1):判断形参coll1中的所有元素是否都存在于当前集合中。
        Collection coll1 = Arrays.asList("cc",456);
        /*Arrays.asList-->在import java.util.ArrayList;是一个工具类,
        返回的是List,而List是Collection中的一个子接口
        相当于一个多态的方式*/
        /*Collection coll1 = Arrays.asList(123,4567);与 Collection coll = new ArrayList();
        含义是差不多的,可以理解为Collection coll1 = Arrays.asList(123,4567);这个方式省去new,且可以直接添加元素
        * */

        System.out.println(coll.containsAll(coll1));
    }
    @Test
    public void test2(){
        //3.remove(Object obj):从当前集合中移除obj元素。
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        coll.remove(1234);
        //remove()方法内部也调用了equals()方法
        System.out.println(coll);

        coll.remove(new Person("Jerry",20));
        System.out.println(coll);

        //4. removeAll(Collection coll1):差集:从当前集合中移除coll1中所有的元素。
        Collection coll1 = Arrays.asList(123,456);
        coll.removeAll(coll1);
        System.out.println(coll);
    }

    @Test
    public void test3(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        //5.retainAll(Collection coll1):交集:获取当前集合和coll1集合的交集,并返回给当前集合
//        Collection coll1 = Arrays.asList(123,456,789);
//        coll.retainAll(coll1);
//        System.out.println(coll);

        //6.equals(Object obj):要想返回true,需要当前集合和形参集合的元素都相同。
        Collection coll1 = new ArrayList();
        //ArrayList()是一个有序的
        coll1.add(456);
        coll1.add(123);
        coll1.add(new Person("Jerry",20));
        coll1.add(new String("Tom"));
        coll1.add(false);

        System.out.println(coll.equals(coll1));
    }
    @Test
    public void test4(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        //7.hashCode():返回当前对象的哈希值
        System.out.println(coll.hashCode());

        //8.集合---->数组的一个转换:toArray()
        Object[] arr = coll.toArray();
        for(int i = 0;i < arr.length;i++){
            System.out.println(arr[i]);
        }

        //拓展:数组 --->集合:调用Arrays类的静态方法asList()
        List<String> list = Arrays.asList(new String[]{"AA", "BB", "CC"});
        System.out.println(list);

        List arr1 = Arrays.asList(123, 456);
        System.out.println(arr1);//[123, 456]

        List arr2 = Arrays.asList(new int[]{123, 456});
        System.out.println(arr2.size());//1

        List arr3 = Arrays.asList(new Integer[]{123, 456});
        System.out.println(arr3.size());//2

        //9.iterator():返回Iterator接口的实例,用于遍历集合元素。放在IteratorTest.java中测试
    }

}


 

package doy1;

/**
 * @author shkstart
 * @create 2021-10-31 15:09
 */
import java.util.Objects;

public class Person {

    private String name;
    private int age;

    public Person() {
        super();
    }

    public Person(String name, int age) {
        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 "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        System.out.println("Person equals()....");
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {

        return Objects.hash(name, age);
    }
}

Iterator迭代器接口

Iterator对象称为迭代器(设计模式的一种),主要用于遍历Collection 集合中的元素。
GOF给迭代器模式的定义为:提供一种方法访问一个容器(container)对象中各个元素,而又不需暴露该对象的内部细节。迭代器模式,就是为容器而生。类似于“公交车上的售票员”、“火车上的乘务员”、“空姐”。
Collection接口继承了java.lang.Iterable接口,该接口有一个iterator()方法,那么所有实现了Collection接口的集合类都有一个iterator()方法,用以返回一个实现了Iterator接口的对象。
Iterator 仅用于遍历集合,Iterator本身并不提供承装对象的能力。如果需要创建Iterator 对象,则必须有一个被迭代的集合。
集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合的第一个元素之前。

 

package doy1;

import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
 * @author shkstart
 * @create 2021-10-31 16:22
 */
public class IteratorTest {
    @Test
    public void test(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        Iterator iterator = coll.iterator();

        //方式一:有几个元素,就调用几个next
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        //报异常:NoSuchElementException
//        //因为:在调用it.next()方法之前必须要调用it.hasNext()进行检测。
//        //若不调用,且下一条记录无效,直接调用it.next()会抛出NoSuchElementException异常。
//        System.out.println(iterator.next());

        //方式二:不推荐
//        for(int i = 0;i < coll.size();i++){
//            System.out.println(iterator.next());
//        }
/**
 * 集合元素的遍历操作,使用迭代器Iterator接口
 * 内部的方法:hasNext()和 next()
 *
 */
        //方式三:推荐
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
    @Test
    public void test2(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        //错误方式一:
//        Iterator iterator = coll.iterator();
//        while(iterator.next() != null){//A
//            System.out.println(iterator.next());//B
//        }
        /*
        方式一错误的原因:
        输出的时候,会跳过数据
        当执行到A的时候,首先会判断,
        而next():---->①指针下移 ②将下移以后集合位置上的元素返回
        所以到A的时候,指针就已经下移了
        而执行到B的时候,在A下移的那个数据,就输出不了,所以这是个错误的方式
            */
        //错误方式二:
        //集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合的第一个元素之前。
        while(coll.iterator().hasNext()){//A
            System.out.println(coll.iterator().next());//B
            /*
            方式二错误的原因:
            当执行到A的时候,没有错误,执行到B的时候,也没有错误,此时输出了第一个元素--->123,
            当再次到A的时候,又得到了一个新的迭代器,到B的时候,又输出了第一个元素--->123,
            此时陷入了一个死循环。
            * */
        }
    }
    @Test
    public void test3(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        //删除集合中”Tom”
        //如果还未调用next()或在上一次调用 next 方法之后已经调用了 remove 方法,
        // 再调用remove都会报IllegalStateException。

        Iterator iterator = coll.iterator();
        while(iterator.hasNext()){
//            iterator.remove();
            //还未调用next()再调用remove都会报IllegalStateException的解释
            /*
            至于这里为什么不能调用remove()--->
            因为在while(iterator.hasNext()),首先创建了一个新的迭代器
            第一个是一个空的(非空指针),此处调用remiove()的话,就会报错----->IllegalStateException。
             */
            Object obj = iterator.next();
            if("Tom".equals(obj)){
                iterator.remove();
//                iterator.remove();
                //上一次调用 next 方法之后已经调用了 remove 方法,再调用remove都会报IllegalStateException。的解释
                /*
                至于为什么调用了一次remove()之后不能在调用一次remove()
                因为在第一个调用的时候,就已经删除了,而第二次的时候,就找不到了,就会报错
                 */
            }
        }

        //遍历集合
        //至于为什么又调用了iterator---->已经指针到最后了,需要重新得到一个Iterator对象,要不然输出的就是为空
        iterator = coll.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }

    }

}

新特性foreach循环遍历集合或数组

  • Java 5.0 提供了foreach循环迭代访问Collection和数组。
  • 遍历操作不需获取Collection或数组的长度,无需使用索引访问元素。
  • 遍历集合的底层调用Iterator完成操作。
  • foreach还可以用来遍历数组
package doy1;

/**
 * @author shkstart
 * @create 2021-10-31 21:59
 */
import org.junit.Test;

import java.util.ArrayList;
import java.util.Collection;

/**
 * jdk 5.0 新增了foreach循环,用于遍历集合、数组
 *
 */
public class ForTest {

    @Test
    public void test(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        //for(集合元素的类型 局部变量 : 集合对象),内部仍然调用了迭代器。
        for(Object obj : coll){
            System.out.println(obj);
        }
    }

    @Test
    public void test2(){
        int[] arr = new int[]{1,2,3,4,5,6};
        //for(数组元素的类型 局部变量 : 数组对象)
        for(int i : arr){
            System.out.println(i);
        }
    }

    //练习题
    @Test
    public void test3(){
        String[] arr = new String[]{"SS","KK","RR"};

//        //方式一:普通for赋值
//        for(int i = 0;i < arr.length;i++){
//            arr[i] = "HH";
//        }

        //方式二:增强for循环
        for(String s : arr){//A
            s = "HH";//B
//            System.out.println(s);
        }
        System.out.println("*******");
        for(int i = 0;i < arr.length;i++){
            System.out.println(arr[i]);//SS KK RR

            /*
            至于为什么最后输出的还是---->SS KK RR,而不是HH的解释
            for(String s : arr)  A中,局部变量是s,到了B的时候,此时的只是给s赋值了
            此时的arr[i]的值并没有改变。
            * */
        }

    }
}

 

 

posted @ 2021-10-31 22:15  浩楠要秃顶  阅读(13)  评论(0编辑  收藏  举报