重踏学习Java路上_Day15(对象数组,集合类,列表)

集合遍历访问:1.对象数组遍历,Aaary.toArray()(对象数组专用);2.集合的size()方法与集合的get(i)的组合进行遍历;3.迭代器(包含Iterator与ListIterator等)遍历;4.增强for

1:对象数组(掌握)
    (1)数组既可以存储基本数据类型,也可以存储引用类型。它存储引用类型的时候的数组就叫对象数组。
    (2)案例:
        用数组存储5个学生对象,并遍历数组。

public class Student {
    // 成员变量
    private String name;
    private int age;

    // 构造方法
    public Student() {
        super();
    }

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

    // 成员方法
    // getXxx()/setXxx()
    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 + "]";
    }
}

/*
 * 我有5个学生,请把这个5个学生的信息存储到数组中,并遍历数组,获取得到每一个学生信息。
 *         学生:Student
 *         成员变量:name,age
 *         构造方法:无参,带参
 *         成员方法:getXxx()/setXxx()
 *         存储学生的数组?自己想想应该是什么样子的?
 * 分析:
 *         A:创建学生类。
 *         B:创建学生数组(对象数组)。
 *         C:创建5个学生对象,并赋值。
 *         D:把C步骤的元素,放到数组中。
 *         E:遍历学生数组。
 */
public class ObjectArrayDemo {
    public static void main(String[] args) {
        // 创建学生数组(对象数组)。
        Student[] students = new Student[5];
        // for (int x = 0; x < students.length; x++) {
        // System.out.println(students[x]);
        // }
        // System.out.println("---------------------");

        // 创建5个学生对象,并赋值。
        Student s1 = new Student("林青霞", 27);
        Student s2 = new Student("风清扬", 30);
        Student s3 = new Student("刘意", 30);
        Student s4 = new Student("赵雅芝", 60);
        Student s5 = new Student("王力宏", 35);

        // 把C步骤的元素,放到数组中。
        students[0] = s1;
        students[1] = s2;
        students[2] = s3;
        students[3] = s4;
        students[4] = s5;

        // 看到很相似,就想循环改
        // for (int x = 0; x < students.length; x++) {
        // students[x] = s + "" + (x + 1);
        // }
        // 这个是有问题的

        // 遍历
        for (int x = 0; x < students.length; x++) {
            //System.out.println(students[x]);
            
            Student s = students[x];
            System.out.println(s.getName()+"---"+s.getAge());
        }
    }
}



2:集合(Collection)(掌握)
 (1)集合的由来?
我们学习的是面向对象语言,而面向对象语言对事物的描述是通过对象体现的,为了方便对多个对象进行操作,我们就必须把这多个对象进行存储。
而要想存储多个对象,就不能是一个基本的变量,而应该是一个容器类型的变量,在我们目前所学过的知识里面,有哪些是容器类型的呢?
数组和StringBuffer。但是呢?StringBuffer的结果是一个字符串,不一定满足我们的要求,所以我们只能选择数组,这就是对象数组。
而对象数组又不能适应变化的需求,因为数组的长度是固定的,这个时候,为了适应变化的需求,Java就提供了集合类供我们使用。
  

 (2)集合和数组的区别?
        A:长度区别
            数组固定
            集合可变
        B:内容区别
            数组可以是基本类型,也可以是引用类型
            集合只能是引用类型
        C:元素内容
            数组只能存储同一种类型
            集合可以存储不同类型(其实集合一般存储的也是同一种类型)
    (3)集合的继承体系结构?
        由于需求不同,Java就提供了不同的集合类。这多个集合类的数据结构不同,但是它们都是要提供存储和遍历功能的,
        我们把它们的共性不断的向上提取,最终就形成了集合的继承体系结构图。
        


        Collection
            |--List
                |--ArrayList
                |--Vector
                |--LinkedList
            |--Set
                |--HashSet
                |--TreeSet
    (4)Collection的功能概述
A:添加功能
boolean add(Object obj):添加一个元素
boolean addAll(Collection c):添加一个集合的元素

B:删除功能
void clear():移除所有元素
 boolean remove(Object o):移除一个元素
boolean removeAll(Collection c):移除一个集合的元素(是一个还是所有)

C:判断功能
boolean contains(Object o):判断集合中是否包含指定的元素
boolean containsAll(Collection c):判断集合中是否包含指定的集合元素(是一个还是所有)
boolean isEmpty():判断集合是否为空

D:获取功能
Iterator<E> iterator()(重点)

E:长度功能
int size():元素的个数

F:交集功能
boolean retainAll(Collection c):两个集合都有的元素?思考元素去哪了,返回的boolean又是什么意思呢?

G:把集合转换为数组
Object[] toArray()


部分例子:

//不包含retainAll,toArray,iterator,containsAll,removeAll方法
    public static void main(String[] args) {
        // 测试不带All的方法

        // 创建集合对象
        // Collection c = new Collection(); //错误,因为接口不能实例化
        Collection c = new ArrayList();

        // boolean add(Object obj):添加一个元素
        // System.out.println("add:"+c.add("hello"));
        c.add("hello");
        c.add("world");
        c.add("java");

        // void clear():移除所有元素
        // c.clear();

        // boolean remove(Object o):移除一个元素
        // System.out.println("remove:" + c.remove("hello"));
        // System.out.println("remove:" + c.remove("javaee"));

        // boolean contains(Object o):判断集合中是否包含指定的元素
        // System.out.println("contains:"+c.contains("hello"));
        // System.out.println("contains:"+c.contains("android"));

        // boolean isEmpty():判断集合是否为空
        // System.out.println("isEmpty:"+c.isEmpty());

        //int size():元素的个数
        System.out.println("size:"+c.size());
        
        System.out.println("c:" + c);
    }

public class CollectionDemo2 {
boolean addAll(Collection c):添加一个集合的元素
boolean removeAll(Collection c):移除一个集合的元素(是一个还是所有)
boolean containsAll(Collection c):判断集合中是否包含指定的集合元素(是一个还是所有)
boolean retainAll(Collection c):两个集合都有的元素?思考元素去哪了,返回的boolean又是什么意思呢?
    public static void main(String[] args) {
        // 创建集合1
        Collection c1 = new ArrayList();
        c1.add("abc1");
        c1.add("abc2");
        c1.add("abc3");
        c1.add("abc4");

        // 创建集合2
        Collection c2 = new ArrayList();
//        c2.add("abc1");
//        c2.add("abc2");
//        c2.add("abc3");
//        c2.add("abc4");
        c2.add("abc5");
        c2.add("abc6");
        c2.add("abc7");

        // boolean addAll(Collection c):添加一个集合的元素
        // System.out.println("addAll:" + c1.addAll(c2));
        
        //boolean removeAll(Collection c):移除一个集合的元素(是一个还是所有)
        //只要有一个元素被移除了,就返回true。
        //System.out.println("removeAll:"+c1.removeAll(c2));

        //boolean containsAll(Collection c):判断集合中是否包含指定的集合元素(是一个还是所有)
        //只有包含所有的元素,才叫包含
        // System.out.println("containsAll:"+c1.containsAll(c2));
        
        //boolean retainAll(Collection c):两个集合都有的元素?思考元素去哪了,返回的boolean又是什么意思呢?
        //假设有两个集合A,B。
        //A对B做交集,最终的结果保存在A中,B不变。
        //返回值表示的是A是否发生过改变。
        System.out.println("retainAll:"+c1.retainAll(c2));
        
        System.out.println("c1:" + c1);
        System.out.println("c2:" + c2);
    }

public static void main(String[] args) {
        集合的遍历。其实就是依次获取集合中的每一个元素。
        Object[] toArray():把集合转成数组,可以实现集合的遍历
        // 创建集合对象
        Collection c = new ArrayList();

        // 添加元素
        c.add("hello"); // Object obj = "hello"; 向上转型
        c.add("world");
        c.add("java");

        // 遍历
        // Object[] toArray():把集合转成数组,可以实现集合的遍历
        Object[] objs = c.toArray();
        for (int x = 0; x < objs.length; x++) {
            // System.out.println(objs[x]);
            // 我知道元素是字符串,我在获取到元素的的同时,还想知道元素的长度。
            // System.out.println(objs[x] + "---" + objs[x].length());
            // 上面的实现不了,原因是Object中没有length()方法
            // 我们要想使用字符串的方法,就必须把元素还原成字符串
            // 向下转型
            String s = (String) objs[x];
            System.out.println(s + "---" + s.length());
        }
    }

面试题:数组有没有length()方法呢?字符串有没有length()方法呢?集合有没有length()方法呢?  
答案:数组没有length()方法,只有length属性,字符串有length()方法,集合没有length()方法,只有size()方法


(5)Collection集合的遍历
A:把集合转数组(了解)

/*
 * 练习:用集合存储5个学生对象,并把学生对象进行遍历。
 *
 * 分析:
 * A:创建学生类
 * B:创建集合对象
 * C:创建学生对象
 * D:把学生添加到集合
 * E:把集合转成数组
 * F:遍历数组
 */
public class StudentDemo {
    public static void main(String[] args) {
        // 创建集合对象
        Collection c = new ArrayList();

        // 创建学生对象
        Student s1 = new Student("林青霞", 27);
        Student s2 = new Student("风清扬", 30);
        Student s3 = new Student("令狐冲", 33);
        Student s4 = new Student("武鑫", 25);
        Student s5 = new Student("刘晓曲", 22);

        // 把学生添加到集合
        c.add(s1);
        c.add(s2);
        c.add(s3);
        c.add(s4);
        c.add(s5);

        // 把集合转成数组
        Object[] objs = c.toArray();
        // 遍历数组
        for (int x = 0; x < objs.length; x++) {
            // System.out.println(objs[x]); //调用这个会有很多很好的子类方法不能调用,所以还是向下转型会比较好
            Student s = (Student) objs[x];
            System.out.println(s.getName() + "---" + s.getAge());
        }
    }
}

B:迭代器(集合专用方式)

Iterator iterator():迭代器,集合的专用遍历方式
Object next():获取元素,并移动到下一个位置。
NoSuchElementException:没有这样的元素,因为你已经找到最后了。
boolean hasNext():如果仍有元素可以迭代,则返回 true。
    public static void main(String[] args) {
        // 创建集合对象
        Collection c = new ArrayList();

        // 创建并添加元素
        // String s = "hello";
        // c.add(s);
        c.add("hello");
        c.add("world");
        c.add("java");

        // Iterator iterator():迭代器,集合的专用遍历方式
        Iterator it = c.iterator(); // 实际返回的肯定是子类对象,这里是多态

        // 最终版代码
        while (it.hasNext()) {
            // System.out.println(it.next());
            String s = (String) it.next();
            System.out.println(s);
        }
    }

学生循环例子:

    public static void main(String[] args) {
        // 创建集合对象
        Collection c = new ArrayList();

        // 创建学生对象
        Student s1 = new Student("林青霞", 27);
        Student s2 = new Student("风清扬", 30);
        Student s3 = new Student("令狐冲", 33);
        Student s4 = new Student("武鑫", 25);
        Student s5 = new Student("刘晓曲", 22);

        // 把学生添加到集合中
        c.add(s1);
        c.add(s2);
        c.add(s3);
        c.add(s4);
        c.add(s5);

        // 遍历
        Iterator it = c.iterator();
        while (it.hasNext()) {
            Student s = (Student) it.next();
            System.out.println(s.getName() + "---" + s.getAge());
            
        * 问题2:不要多次使用it.next()方法,因为每次使用都是访问一个对象。
            // NoSuchElementException 不要多次使用it.next()方法
            // System.out.println(((Student) it.next()).getName() + "---"
            // + ((Student) it.next()).getAge());

        }
        // System.out.println("----------------------------------");
        * 问题1:能用while循环写这个程序,我能不能用for循环呢?  其实用for是最好的,因为for()括号内的语句块内容能在语句块运行完后马上被收回,减少内存损耗,而while写法,因为迭代器在外部定义,所以外部变量没有马上消失并回收
        // for循环改写
        // for(Iterator it = c.iterator();it.hasNext();){
        // Student s = (Student) it.next();
        // System.out.println(s.getName() + "---" + s.getAge());
        // }
    }

 集合遍历的全部方法

    public static void main(String[] args) {
        ArrayList<String> array = new ArrayList<String>();
        array.add("Hello");
        array.add("World");
        array.add("Java");
        
        //普通for
        for(int i = 0;i<array.size();i++){
            String s =array.get(i);
            System.out.println(s);
        }
        //迭代器
        Iterator<String> it = array.iterator();
        
        while(it.hasNext()){
            String s = it.next();
            System.out.println(s);
        }
        
        //增强for
        for(String s : array){
            System.out.println(s);
        }
    }


(6)迭代器
        A:是集合的获取元素的方式。
        B:是依赖于集合而存在的。
        C:迭代器的原理和源码。
            a:为什么定义为了一个接口而不是实现类? 因为实现具体类的方法各不相同,但每个类的迭代方式都需要相同的三个方法,所以用接口较为恰当与合适
            b:看了看迭代器的内部类实现。

/*
 * 需求:存储字符串并遍历。
 *
 * 分析:
 *         A:创建集合对象
 *         B:创建字符串对象
 *         C:把字符串对象添加到集合中
 *         D:遍历集合
 */
public class CollectionTest {
    public static void main(String[] args) {
        // 创建集合对象
        Collection c = new ArrayList();

        // 创建字符串对象
        // 把字符串对象添加到集合中
        c.add("林青霞");
        c.add("风清扬");
        c.add("刘意");
        c.add("武鑫");
        c.add("刘晓曲");

        // 遍历集合
        // 通过集合对象获取迭代器对象
        Iterator it = c.iterator();
        // 通过迭代器对象的hasNext()方法判断有没有元素
        while (it.hasNext()) {
            // 通过迭代器对象的next()方法获取元素
            String s = (String) it.next();
            System.out.println(s);
        }
    }
}

/*
 * 需求:存储自定义对象并遍历Student(name,age)
 *
 * 分析:
 *         A:创建学生类
 *         B:创建集合对象
 *         C:创建学生对象
 *         D:把学生对象添加到集合对象中
 *         E:遍历集合
 */
public class CollectionTest2 {
    public static void main(String[] args) {
        // 创建集合对象
        Collection c = new ArrayList();

        // 创建学生对象
        Student s1 = new Student("貂蝉", 25);
        Student s2 = new Student("小乔", 16);
        Student s3 = new Student("黄月英", 20);
        Student s4 = new Student();
        s4.setName("大乔");
        s4.setAge(26);

        // 把学生对象添加到集合对象中
        c.add(s1);
        c.add(s2);
        c.add(s3);
        c.add(s4);
        c.add(new Student("孙尚香", 18)); // 匿名对象

        // 遍历集合
        Iterator it = c.iterator();
        while (it.hasNext()) {
            Student s = (Student) it.next();
            System.out.println(s.getName() + "---" + s.getAge());
        }
    }
}----------------------------------------------------------
迭代器的原理和源码
public interface Inteator {  //接口源码
    boolean hasNext();
    Object next();
}

public interface Iterable { //实现接口的封装
    Iterator iterator();
}

public interface Collection extends Iterable { //继承子接口
    Iterator iterator();
}

public interface List extends Collection {  //继承子接口
    Iterator iterator();
}

public class ArrayList implements List {  //实现接口
    public Iterator iterator() {
        return new Itr();  //返回实现类
    }
    
    private class Itr implements Iterator {  //内部类子类实现接口,多态的表现
        public boolean hasNext() {}
        public Object next(){}
    }
}


Collection c = new ArrayList();
c.add("hello");
c.add("world");
c.add("java");
Iterator it = c.iterator();     //其实这里调用了new Itr()子类实现类
while(it.hasNext()) {
    String s = (String)it.next();
    System.out.println(s);
}
--------------------------------------------------


    (7)Collection集合的案例(遍历方式 迭代器)
        集合的操作步骤:
            A:创建集合对象
            B:创建元素对象
            C:把元素添加到集合
            D:遍历集合
    
        A:存储字符串并遍历
            import java.util.Collection;
            import java.util.ArrayList;
            import java.util.Iterator;
            
            public class CollectionDemo {
                public static void main(String[] args) {
                    //创建集合对象
                    Collection c = new ArrayList();
                    
                    //创建并添加元素
                    c.add("hello");
                    c.add("world");
                    c.add("java");
                    
                    //遍历集合
                    Iterator it = c.iterator();
                    while(it.hasNext()) {
                        String s =(String) it.next();
                        System.out.println(s);
                    }
                }
            }
        
        B:存储自定义对象并遍历
            public class Student {
                private String name;
                private int age;
                
                public Student(){}
                
                public Student(String name,int age) {
                    this.name = name;
                    this.age = age;
                }
                
                //getXxx()/setXxx()
            }
            
            import java.util.Collection;
            import java.util.ArrayList;
            import java.util.Iterator;
            
            public class StudentDemo {
                public static void main(String[] args) {
                    //创建集合对象
                    Collection c = new ArrayList();
                    
                    //创建学生对象
                    Student s1 = new Student("林青霞",27);
                    Student s2 = new Student("风清扬",30);
                    Student s3 = new Student("刘意",30);
                    Student s4 = new Student("武鑫",25);
                    Student s5 = new Student("刘晓曲",16);
                    
                    //添加元素
                    c.add(s1);
                    c.add(s2);
                    c.add(s3);
                    c.add(s4);
                    c.add(s5);
                    
                    //遍历集合
                    Iterator it = c.iterator();
                    while(it.hasNext()) {
                        Student s = (Student)it.next();
                        System.out.println(s.getName()+"---"+s.getAge());
                    }
                }
            }

3:集合(List)(掌握)
    (1)List是Collection的子接口
        特点:有序(存储顺序和取出顺序一致),可重复。有序的 collection(也称为序列)。此接口的用户可以对列表中每个元素的插入位置进行精确地控制。用户可以根据元素的整数索引(在列表中的位置)访问元素,并搜索列表中的元素。与 set 不同,列表通常允许重复的元素。

(2)List的特有功能:
/*
 * List集合的特有功能:
 * A:添加功能
 *         void add(int index,Object element):在指定位置添加元素
 * B:获取功能
 *         Object get(int index):获取指定位置的元素
 * C:列表迭代器
 *         ListIterator listIterator():List集合特有的迭代器
 * D:删除功能
 *         Object remove(int index):根据索引删除元素,返回被删除的元素
 * E:修改功能
 *         Object set(int index,Object element):根据索引修改元素,返回被修饰的元素
 */
    public static void main(String[] args) {
        // 创建集合对象
        List list = new ArrayList();

        // 添加元素
        list.add("hello");
        list.add("world");
        list.add("java");

        // void add(int index,Object element):在指定位置添加元素
        // list.add(1, "android");//没有问题
        // IndexOutOfBoundsException
        // list.add(11, "javaee");//有问题
        // list.add(3, "javaee"); //没有问题
        // list.add(4, "javaee"); //有问题

        // Object get(int index):获取指定位置的元素
        // System.out.println("get:" + list.get(1));
        // IndexOutOfBoundsException
        // System.out.println("get:" + list.get(11));

        // Object remove(int index):根据索引删除元素,返回被删除的元素
        // System.out.println("remove:" + list.remove(1));
        // IndexOutOfBoundsException
        // System.out.println("remove:" + list.remove(11));

        // Object set(int index,Object element):根据索引修改元素,返回被修饰的元素
        System.out.println("set:" + list.set(1, "javaee"));

        System.out.println("list:" + list);
    }


(3)List集合的特有遍历功能
        A:由size()和get()结合。
        B:代码演示
                    //创建集合对象
                    List list = new ArrayList();
                    
                    //创建并添加元素
                    list.add("hello");
                    list.add("world");
                    list.add("java");
                    
                    //Iterator遍历集合
                    Iterator it = list.iterator();
                    while(it.hasNext()) {
                        String s =(String) it.next();
                        System.out.println(s);
                    }
                    System.out.println("----------");


                    //for遍历集合
                    for(int x=0; x<list.size(); x++) {
                        String s =(String) list.get(x);
                        System.out.println(s);
                    }
    (4)列表迭代器的特有功能;(了解)
        可以逆向遍历,但是要先正向遍历,所以无意义,基本不使用

        while (lit.hasPrevious()) {
            String s = (String) lit.previous();
            System.out.println(s);
        }
        System.out.println("-----------------");

        // 迭代器
        Iterator it = list.iterator();
        while (it.hasNext()) {
            String s = (String) it.next();
            System.out.println(s);
        }
        System.out.println("-----------------");


    (5)并发修改异常
        A:出现的现象
            迭代器遍历集合,集合修改集合元素
        B:原因
            迭代器是依赖于集合的,而集合的改变迭代器并不知道。
        C:解决方案
            a:迭代器遍历,迭代器修改(ListIterator)
                元素添加在刚才迭代的位置
            b:集合遍历,集合修改(size()和get())
                元素添加在集合的末尾

/*
 * 问题?
 *         我有一个集合,如下,请问,我想判断里面有没有"world"这个元素,如果有,我就添加一个"javaee"元素,请写代码实现。
 *
 * ConcurrentModificationException:并行修改异常,当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。
 * 产生的原因:
 *         迭代器是依赖于集合而存在的,在判断成功后,集合的中新添加了元素,而迭代器却不知道,所以就报错了,这个错叫并发修改异常。
 *         其实这个问题描述的是:迭代器遍历元素的时候,通过集合是不能修改元素的。
 * 如何解决呢?
 *         A:迭代器迭代元素,迭代器修改元素
 *             元素是跟在刚才迭代的元素后面的。
 *         B:集合遍历元素,集合修改元素(普通for)
 *             元素在最后添加的。
 */
public class ListIteratorDemo2 {
    public static void main(String[] args) {
        // 创建List集合对象
        List list = new ArrayList();
        // 添加元素
        list.add("hello");
        list.add("world");
        list.add("java");

        // 迭代器遍历
        // Iterator it = list.iterator();
        // while (it.hasNext()) {
        // String s = (String) it.next();
        // if ("world".equals(s)) {
        // list.add("javaee");//报错并发修改异常
        // }
        // }

        // 方式1:迭代器迭代元素,迭代器修改元素
        而Iterator迭代器却没有添加功能,所以我们使用其子接口ListIterator
        ListIterator lit = list.listIterator();
        while (lit.hasNext()) {
        String s = (String) lit.next();
        if ("world".equals(s)) {
        lit.add("javaee");
        }
        }

        // 方式2:集合遍历元素,集合修改元素(普通for)
        for (int x = 0; x < list.size(); x++) {
            String s = (String) list.get(x);
            if ("world".equals(s)) {
                list.add("javaee");
            }
        }

        System.out.println("list:" + list);
    }
}


(6)常见数据结构
        A:栈       先进后出
        B:队列    先进先出
        C:数组    查询快,增删慢
        D:链表    查询慢,增删快

 (7)List的子类特点(面试题)
List:(面试题List的子类特点)
    ArrayList:
        底层数据结构是数组,查询快,增删慢。
        线程不安全,效率高。
    Vector:
        底层数据结构是数组,查询快,增删慢。
        线程安全,效率低。
    LinkedList:
        底层数据结构是链表,查询慢,增删快。
        线程不安全,效率高。
        
    List有三个儿子,我们到底使用谁呢?
        看需求(情况)。
        
    要安全吗?
        要:Vector(即使要安全,也不用这个了,后面有替代的)
        不要:ArrayList或者LinkedList
            查询多:ArrayList
            增删多:LinkedList
            
    如果你什么都不懂,就用ArrayList。


    (8)List集合的案例(遍历方式:迭代器和普通for) 上面的代码已经有了
        A:存储字符串并遍历
        B:存储自定义对象并遍历

原文地址:https://www.cnblogs.com/canceler/p/4615275.html