【原】Java学习笔记026 - 集合

 1 package cn.temptation;
 2 
 3 public class Sample01 {
 4     public static void main(String[] args) {
 5         // 需求:从三国演义中评选出四个最帅的武将,并存储下来
 6         
 7         // 因为具备了面向对象的思想,所以创建四个对象来存储
 8         Hero hero1 = new Hero("张飞", 18);
 9         Hero hero2 = new Hero("赵云", 16);
10         Hero hero3 = new Hero("陆逊", 17);
11         Hero hero4 = new Hero("张辽", 20);
12         
13         // 因为这四个对象有着相同的语义,所以考虑把它们放在一个数组中,对象的数组简称对象数组
14         Hero[] heros = new Hero[4];
15         System.out.println(heros);        // [Lcn.temptation.Hero;@15db9742
16         
17         heros[0] = hero1;
18         heros[1] = hero2;
19         heros[2] = hero3;
20         heros[3] = hero4;
21         
22         // 一般for循环的遍历
23         for (int i = 0; i < heros.length; i++) {
24             Hero item = heros[i];
25             System.out.println(item);
26         }
27         
28         // 增强型for循环的遍历
29         for (Hero item : heros) {
30             System.out.println(item);
31         }
32     }
33 }
34 
35 // 英雄类
36 class Hero {
37     // 成员变量
38     private String name;
39     private int age;
40 
41     // 构造函数
42     public Hero() {
43         super();
44     }
45 
46     public Hero(String name, int age) {
47         super();
48         this.name = name;
49         this.age = age;
50     }
51 
52     // 成员方法
53     public String getName() {
54         return name;
55     }
56 
57     public void setName(String name) {
58         this.name = name;
59     }
60 
61     public int getAge() {
62         return age;
63     }
64 
65     public void setAge(int age) {
66         this.age = age;
67     }
68 
69     @Override
70     public String toString() {
71         return "武将 [姓名:" + name + ", 年龄:" + age + "]";
72     }
73 }
  1 package cn.temptation;
  2 
  3 import java.util.ArrayList;
  4 import java.util.Collection;
  5 
  6 public class Sample02 {
  7     public static void main(String[] args) {
  8         /*
  9          * 问题:
 10          * 选出四大帅哥武将后,张飞被杀,然后大家重新选,有两个人票数相同,变成五大帅哥武将
 11          * 这时,数据存储的数组出现问题了,之前设置的长度为4,现在要放入5个元素,不得不修改数组的长度
 12          * 像这样的数组长度的变化对于使用起来很不方便
 13          * 
 14          * 针对这类问题,Java提供了适应变化的解决方案-----集合
 15          * 
 16          * 数组  和  集合 的区别:
 17          * 1、长度上的区别:数组长度固定,集合长度不固定(可变的)
 18          * 2、元素上的区别:数组的元素都是同一类型,集合的元素可以是不同类型的
 19          * 3、元素的数据类型上的区别:数组的元素的数据类型可以是基本数据类型、也可以是引用数据类型;集合的元素的数据类型只能是引用数据类型
 20          * 
 21          * 集合相关的接口 和 类  都位于 java.util 中
 22          * 
 23          * 集合中的接口 和 实现类很多,如何掌握?从上向下进行学习? 还是从下向上进行学习?
 24          * 这里选择从上向下进行学习,从根接口开始,每一级子接口只要学习一下父接口中没有的特性方法就可以了
 25          * 
 26          * 集合可以分为    单列集合(根接口:Collection接口)     和    双列集合(根接口:Map接口)
 27          * 
 28          * Collection接口:Collection 层次结构 中的根接口。Collection 表示一组对象,这些对象也称为 collection 的元素。
 29          * 一些 collection 允许有重复的元素,而另一些则不允许。一些 collection 是有序的,而另一些则是无序的。
 30          * JDK 不提供此接口的任何直接 实现:它提供更具体的子接口(如 Set 和 List)实现。
 31          * 此接口通常用来传递 collection,并在需要最大普遍性的地方操作这些 collection。 
 32          * 
 33          * Collection接口的常用成员方法:
 34          * 1、容量
 35          * int size() :返回此 collection 中的元素数。 
 36          * 
 37          * 2、添加功能
 38          * boolean add(E e) :确保此 collection 包含指定的元素(可选操作)。 
 39          * 
 40          * 3、删除功能
 41          * void clear() :移除此 collection 中的所有元素(可选操作)。
 42          * boolean remove(Object o) :从此 collection 中移除指定元素的单个实例,如果存在的话(可选操作)。  
 43          * 
 44          * 4、判断功能
 45          * boolean contains(Object o) :如果此 collection 包含指定的元素,则返回 true。
 46          * boolean isEmpty() :如果此 collection 不包含元素,则返回 true。  
 47          * 
 48          */
 49         
 50         // 创建Collection接口类型的对象,因为Collection接口没有任何直接实现类,所以在其子接口List 和 Set上找实现类,找到实现List接口的ArrayList类
 51         Collection collection = new ArrayList();
 52         System.out.println("collection:" + collection);        // collection:[]
 53         
 54         // 添加功能
 55         collection.add("China");
 56         collection.add("USA");
 57         collection.add("Japan");
 58         
 59         System.out.println("add:" + collection.add("England"));        // add:true
 60         
 61         System.out.println("size:" + collection.size());
 62         
 63         // 查看源码,会列出全部实现了Collection接口的add方法的各种子接口或实现类,选择ArrayList
 64 //        public boolean add(E e) {
 65 //            ensureCapacityInternal(size + 1);  // Increments modCount!!
 66 //            elementData[size++] = e;
 67 //            return true;
 68 //        }
 69         
 70         System.out.println("-------------------------------------------------------");
 71         
 72         // 删除功能
 73 //        collection.clear();
 74         
 75         System.out.println("remove:" + collection.remove("Japan"));            // true
 76         System.out.println("remove:" + collection.remove("France"));        // false
 77         
 78         System.out.println("size:" + collection.size());
 79         
 80         System.out.println("-------------------------------------------------------");
 81         
 82         // 判断功能
 83         System.out.println("contains:" + collection.contains("China"));        // true
 84         System.out.println("contains:" + collection.contains("France"));    // false
 85         
 86         System.out.println("isEmpty:" + collection.isEmpty());                // false
 87         
 88         System.out.println("collection:" + collection);
 89         
 90         System.out.println("-------------------------------------------------------");
 91         
 92         // 【比较数组、字符串、字符串缓冲区、集合用来描述容量或长度的方法或属性】
 93         // 1、数组:长度       length属性,注意不是length()方法
 94         // 2、字符串:长度    length()方法
 95         // 3、字符串缓冲区:容量 capacity() ----- 设定值;长度length(),实际值
 96         // 4、集合:长度(元素数量)size()
 97         
 98         int[] arr = new int[3];
 99         System.out.println(arr.length);                    // 3
100         
101         String str = "123";
102         System.out.println(str.length());                // 3
103         
104         StringBuffer sb = new StringBuffer(str);
105         System.out.println(sb.capacity());                // 19
106         System.out.println(sb.length());                // 3
107     }
108 }
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 
 6 public class Sample03 {
 7     public static void main(String[] args) {
 8         /*
 9          * Collection接口的常用成员方法:
10          * 1、添加功能
11          * boolean addAll(Collection<? extends E> c) :将指定 collection 中的所有元素都添加到此 collection 中(可选操作)。 
12          * 
13          * 2、删除功能
14          * boolean removeAll(Collection<?> c) :移除此 collection 中那些也包含在指定 collection 中的所有元素(可选操作)。 
15          * 
16          * 3、判断功能
17          * boolean containsAll(Collection<?> c) :如果此 collection 包含指定 collection 中的所有元素,则返回 true。 
18          * 
19          * 4、交集功能
20          * boolean retainAll(Collection<?> c) :仅保留此 collection 中那些也包含在指定 collection 的元素(可选操作)。 
21          */
22         
23         Collection collection1 = new ArrayList();
24         collection1.add("中国");
25         collection1.add("美国");
26         System.out.println("collection1:" + collection1);        // collection1:[中国, 美国]
27         
28         Collection collection2 = new ArrayList();
29         collection2.add("中国");
30         collection2.add("德国");
31         System.out.println("collection2:" + collection2);        // collection2:[中国, 德国]
32         
33         // 添加功能:把作为形参的集合的全部元素都加入到原集合中,不论是否重复
34         collection1.addAll(collection2);
35         System.out.println("collection1:" + collection1);        // collection1:[中国, 美国, 中国, 德国]
36         System.out.println("collection2:" + collection2);        // collection2:[中国, 德国]
37         
38         // addAll()方法返回:如果此 collection 由于调用而发生更改,则返回 true
39         //(原集合中只要添加了至少一个元素,就返回true,如果原集合中一个元素都没有改变,就返回false) 
40         Collection collection3 = new ArrayList();
41         System.out.println("collection1:" + collection1.addAll(collection3));        // collection1:false
42         
43         System.out.println("-------------------------------------------------");
44         
45         Collection collection4 = new ArrayList();
46         collection4.add("中国");
47         collection4.add("美国");
48         
49         // 删除功能:把作为形参的集合的全部元素和原集合中的元素进行比较,剔除相同的元素
50         collection1.removeAll(collection4);
51         System.out.println("collection1:" + collection1);        // collection1:[德国]
52         System.out.println("collection4:" + collection4);        // collection4:[中国, 美国]
53         
54         // removeAll()方法返回:如果此 collection 由于调用而发生更改,则返回 true 
55         Collection collection5 = new ArrayList();
56         System.out.println("collection1:" + collection1.removeAll(collection5));        // collection1:false
57         
58         System.out.println("-------------------------------------------------");
59         
60         Collection collection6 = new ArrayList();
61         collection6.add("德国");
62         
63         // 判断功能:如果此集合包含指定集合中的所有元素,则返回true(子集关系)
64         System.out.println("containsAll:" + collection1.containsAll(collection6));        // containsAll:true
65         
66         collection6.add("俄罗斯");
67         System.out.println("containsAll:" + collection1.containsAll(collection6));        // containsAll:false
68         
69         System.out.println("-------------------------------------------------");
70         
71         Collection collection7 = new ArrayList();
72         collection7.add("中国");
73         collection7.add("日本");
74         
75         collection1.add("中国");
76         
77         System.out.println("collection1:" + collection1);                    // collection1:[德国, 中国]    
78         System.out.println("collection7:" + collection7);                    // collection7:[中国, 日本]
79         
80         System.out.println("retainAll:" + collection1.retainAll(collection7));        // retainAll:true
81         
82         System.out.println("collection1:" + collection1);                    // collection1:[中国]
83         System.out.println("collection7:" + collection7);                    // collection7:[中国, 日本]
84         
85         Collection collection8 = new ArrayList();
86         collection8.add("中国");
87         
88         System.out.println("collection1:" + collection1);                    // collection1:[中国]
89         System.out.println("collection8:" + collection8);                    // collection8:[中国]
90         
91         System.out.println("retainAll:" + collection1.retainAll(collection8));        // retainAll:false
92         
93         // 交集功能:如果原集合因为和指定集合获取相同的元素而让自身的元素个数发生改变,则返回true,否则返回false
94     }
95 }
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 
 6 public class Sample04 {
 7     public static void main(String[] args) {
 8         /*
 9          * Collection接口的常用成员方法:
10          * 1、Object[] toArray() :返回包含此 collection 中所有元素的数组。 
11          */
12         Collection collection = new ArrayList();
13         
14         collection.add("中国");
15         collection.add("美国");
16         collection.add("德国");
17         
18         Object[] arr = collection.toArray();
19         
20         for (int i = 0; i < arr.length; i++) {
21             System.out.println(arr[i]);
22         }
23         
24         for (Object item : arr) {
25             System.out.println(item);
26         }
27     }
28 }
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 
 6 public class Sample05 {
 7     public static void main(String[] args) {
 8         /*
 9          * Collection接口的常用成员方法:
10          * 1、Object[] toArray() :返回包含此 collection 中所有元素的数组。 
11          */
12         Collection collection = new ArrayList();
13         
14         Student student1 = new Student("吕布", 20);
15         Student student2 = new Student("貂蝉", 16);
16         
17         collection.add(student1);
18         collection.add(student2);
19         
20         System.out.println(collection);            // [学生 [姓名为:吕布, 年龄为:20], 学生 [姓名为:貂蝉, 年龄为:16]]
21         
22         Object[] arr = collection.toArray();
23         
24         // 增强型for循环
25         for (Object item : arr) {
26             // 下面两句效果相同,因为item实际就是Student类类型的对象
27 //            System.out.println(item);
28             System.out.println((Student)item);
29         }
30         
31         // 一般for循环
32         for (int i = 0; i < arr.length; i++) {
33             // 写法1
34 //            System.out.println(arr[i]);
35             // 写法2:定义Student类型的变量,使用向下转型
36             Student temp = (Student) arr[i];
37             System.out.println(temp);
38         }
39     }
40 }
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 import java.util.Iterator;
 6 
 7 public class Sample06 {
 8     public static void main(String[] args) {
 9         /*
10          * Collection接口的常用成员方法:
11          * 1、Iterator<E> iterator() :返回在此 collection 的元素上进行迭代的迭代器。 
12          * 
13          * 迭代器 Iterator 接口:对 collection 进行迭代的迭代器。迭代器取代了 Java Collections Framework 中的 Enumeration。
14          * 
15          * 迭代:重复反馈的活动,其目的通常是为了逼近所需目标或结果。每次对过程的重复称为一次"迭代"。而每次迭代得到的结果会作为下一次迭代的初始值。
16          * 
17          * Iterator接口的常用成员方法:
18          * 1、boolean hasNext() :如果仍有元素可以迭代,则返回 true。 
19          * 2、Object next() :返回迭代的下一个元素。 
20          * 
21          */
22         
23         Collection collection = new ArrayList();
24         collection.add("China");
25         collection.add("USA");
26         collection.add("Japan");
27         
28         for (Object item : collection) {
29             System.out.println(item);
30         }
31         
32         System.out.println("-------------------------------------------");
33         
34         Iterator iterator = collection.iterator();
35         
36 //        Object obj1 = iterator.next();
37 //        System.out.println(obj1);            // China
38 //        
39 //        Object obj2 = iterator.next();
40 //        System.out.println(obj2);            // USA
41 //        
42 //        Object obj3 = iterator.next();
43 //        System.out.println(obj3);            // Japan
44         
45         // 执行异常:java.util.NoSuchElementException
46 //        Object obj4 = iterator.next();
47 //        System.out.println(obj4);
48         
49         // 因为使用Iterator对象的next()方法,操作获取下一个元素时可能会发生异常,所以需要先判断一下下一个元素是否可以迭代获取
50 //        if (iterator.hasNext()) {
51 //            System.out.println(iterator.next());
52 //        }
53 //        
54 //        if (iterator.hasNext()) {
55 //            System.out.println(iterator.next());
56 //        }
57 //        
58 //        if (iterator.hasNext()) {
59 //            System.out.println(iterator.next());
60 //        }
61 //        
62 //        if (iterator.hasNext()) {
63 //            // 因为collection对象中只有三个元素,所以这里的iterator.hasNext()返回false,也就不会再操作next方法
64 //            System.out.println(iterator.next());
65 //        }
66         
67         // 上面写法比较傻,进行改进:重复的操作可以考虑使用循环
68         while (iterator.hasNext()) {
69             System.out.println(iterator.next());
70         }
71         
72         // 联想一下Scanner类,也有hasNext方法和next方法,查看一下,发现Scanner类实现了Iterator接口
73     }
74 }
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 import java.util.Iterator;
 6 
 7 public class Sample07 {
 8     public static void main(String[] args) {
 9         Collection collection = new ArrayList();
10         
11         collection.add(new Student("张三", 18));
12         collection.add(new Student("李四", 20));
13         collection.add(new Student("王五", 16));
14         collection.add(new Student("赵六", 22));
15         
16         Iterator iterator = collection.iterator();
17         
18         // 写法1、使用while循环进行迭代
19 //        while (iterator.hasNext()) {
20 //            // 写法1-1
21 //            System.out.println(iterator.next());
22 //            
23 //            // 写法1-2
24 ////            Student student = (Student) iterator.next();
25 ////            System.out.println(student);
26 //        }
27         
28         System.out.println("-------------------------------------");
29         
30         // 写法2、使用一般for循环进行迭代,考虑到while循环和for循环其实是一样的
31 //        for (; iterator.hasNext(); ) {
32 //            System.out.println(iterator.next());
33 //        }
34         
35         System.out.println("-------------------------------------");
36         
37         // 写法3、使用eclipse提供的for循环迭代Collection的模板
38 //        for (Iterator iteratorEx = collection.iterator(); iteratorEx.hasNext();) {
39 //            System.out.println(iteratorEx.next());
40 //        }
41         
42         // 错误的写法
43         // 对于集合是奇数元素,这样的写法产生执行异常:java.util.NoSuchElementException
44         // 对于集合是偶数元素,会显示实际元素数量的一半,且数据不正确
45         // 原因:
46         // iterator.next()这个方法不调用不执行,调用了自然要获取下一个元素,48行语句中有两次对iterator.next()方法的调用
47         while (iterator.hasNext()) {
48             System.out.println("姓名为:"  + ((Student)(iterator.next())).getName() + ",年龄为:"  + ((Student)(iterator.next())).getAge());
49         }
50     }
51 }
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 import java.util.Iterator;
 6 
 7 public class Sample08 {
 8     public static void main(String[] args) {
 9         Collection collection = new ArrayList();
10         collection.add("China");
11         collection.add("USA");
12         collection.add("Japan");
13         
14         Iterator iterator = collection.iterator();
15         
16         // 为什么迭代器要设计成这样?
17         // 1、为什么设计为接口?因为接口描述的是后天具备的能力,灵活性很好,只要实现了接口定义的方法就具备了接口的能力
18         // 2、为什么接口最终的实现是在各个集合的具体实现类中创建类的内部类对象?
19         //         集合中接口很多,最终实现类也很多,各种实现类的结构会有所不同,不定义具体的实现,只通过接口定义实现的方法声明,给予各个实现类独立实现
20         //        在各个实现类的内部通过内部类的形式,可以让内部类很方便的访问到其所在的外部类的成员
21     }
22 }
23 
24 // 查看迭代器Iterator接口的源码
25 //public interface Iterator<E> {
26 //    boolean hasNext();
27 //    E next();
28 //}
29 
30 // 查看可迭代接口 Iterable接口的源码
31 //public interface Iterable {
32 //    Iterator<T> iterator();
33 //}
34 
35 // 查看ArrayList类的源码
36 //public Iterator<E> iterator() {
37 //    return new Itr();
38 //}
39 
40 // 查看内部类Itr类的源码
41 //private class Itr implements Iterator<E> {
42 //    int cursor;       // index of next element to return                    游标   指针
43 //    int lastRet = -1; // index of last element returned; -1 if no such
44 //    int expectedModCount = modCount;
45 //
46 //    public boolean hasNext() {
47 //        return cursor != size;
48 //    }
49 //
50 //    @SuppressWarnings("unchecked")
51 //    public E next() {
52 //        checkForComodification();
53 //        int i = cursor;
54 //        if (i >= size)
55 //            throw new NoSuchElementException();
56 //        Object[] elementData = ArrayList.this.elementData;
57 //        if (i >= elementData.length)
58 //            throw new ConcurrentModificationException();
59 //        cursor = i + 1;
60 //        return (E) elementData[lastRet = i];
61 //    }
62 //}
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Iterator;
 5 import java.util.List;
 6 
 7 public class Sample09 {
 8     public static void main(String[] args) {
 9         /*
10          * List接口:继承自Collection接口 和 Iterable接口(多继承)
11          * 有序的 collection(也称为序列)。
12          * 此接口的用户可以对列表中每个元素的插入位置进行精确地控制。
13          * 用户可以根据元素的整数索引(在列表中的位置)访问元素,并搜索列表中的元素。
14          * 
15          * 与 set接口不同,列表通常允许重复的元素。
16          */
17         List list = new ArrayList();
18         
19         list.add("中国");
20         list.add("美国");
21         
22         System.out.println("list:" + list);            // list:[中国, 美国]
23         
24         Iterator iterator = list.iterator();
25         
26         while (iterator.hasNext()) {
27             // 写法1
28 //            System.out.println(iterator.next());
29             
30             // 写法2
31             String str = (String) iterator.next();
32             System.out.println(str);
33         }
34     }
35 }
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Iterator;
 5 import java.util.List;
 6 
 7 public class Sample10 {
 8     public static void main(String[] args) {
 9         /*
10          * List接口的特点:
11          * 1、有序性:元素放入List集合中的顺序   和  遍历List集合时看到的顺序是一致
12          * 2、可重复性:元素的内容可以相同
13          */
14         
15         List list = new ArrayList();
16         
17         list.add("艾欧尼亚");
18         list.add("黑色玫瑰");
19         list.add("皮城警备");
20         list.add("黑色玫瑰");
21         
22         Iterator iterator = list.iterator();
23         
24         while (iterator.hasNext()) {
25             System.out.println(iterator.next());
26         }
27     }
28 }
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Iterator;
 5 import java.util.List;
 6 
 7 public class Sample11 {
 8     public static void main(String[] args) {
 9         List list = new ArrayList();
10         
11         list.add(new Student("张三", 16));
12         list.add(new Student("李四", 18));
13         list.add(new Student("王五", 20));
14         list.add(new Student("李四", 18));
15         
16         Iterator iterator = list.iterator();
17         
18         while (iterator.hasNext()) {
19             Student temp = (Student) iterator.next();
20             System.out.println(temp);
21         }
22     }
23 }
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Iterator;
 5 
 6 public class Sample12 {
 7     public static void main(String[] args) {
 8         /*
 9          * List接口的常用三个实现类:
10          * 1、ArrayList类:
11          *         List 接口的大小可变数组的实现。实现了所有可选列表操作,并允许包括 null 在内的所有元素。
12          *         除了实现 List 接口外,此类还提供一些方法来操作内部用来存储列表的数组的大小。
13          *         底层实现通过数组这个数据结构
14          * 
15          * 2、Vector类:
16          *         Vector 类可以实现可增长的对象数组。与数组一样,它包含可以使用整数索引进行访问的组件。
17          *         但是,Vector 的大小可以根据需要增大或缩小,以适应创建 Vector 后进行添加或移除项的操作。
18          *         底层实现通过数组这个数据结构
19          * 
20          * 3、LinkedList类:
21          *         List 接口的链接列表实现。实现所有可选的列表操作,并且允许所有元素(包括 null)。
22          *         除了实现 List 接口外,LinkedList 类还为在列表的开头及结尾 get、remove 和 insert 元素提供了统一的命名方法。
23          *         这些操作允许将链接列表用作堆栈、队列或双端队列。
24          *         底层实现通过链表这个数据结构
25          * 
26          * 数据结构:
27          * 1、数组:存储同一种类型的多个元素的容器
28          *         int[] arr = { 99, 98, 97 };
29          *         存储形式:    99        98        97
30          *         索引:        0        1        2
31          *         使用场景1、获取元素内容为98的元素,通过索引直接找到元素arr[1]
32          *         使用场景2、在元素内容为98的元素后添加一个元素内容为96,操作步骤如下:
33          *                 A:定义一个新数组,长度为  3 + 1 = 4
34          *                 B:在原数组中找到内容为98的元素及其之前的所有元素,全部复制到新数组中存储下来
35          *                 C:在新数组中添加内容为96的元素
36          *                 D:在原数组中找到内容为98的元素之后的所有元素,复制到新数组中存储下来(索引都要加1)
37          *                 存储形式:    99        98        96        97
38          *                 索引:        0        1        2        3
39          *         使用场景3、在初始数组中删除元素内容为98,操作步骤如下:
40          *                 A:定义一个新数组,长度为  3 - 1 = 2
41          *                 B:在原数组中找到内容为98的元素之前的所有元素,全部复制到新数组中存储下来
42          *                 C:找到内容为98的元素,不复制到新数组中
43          *                 D:在原数组中找到内容为98的元素之后的所有元素,复制到新数组中存储下来(索引都要减1)
44          *                 存储形式:    99        97
45          *                 索引:        0        1
46          * 
47          *      数组结构的特点:查找快速高效、增删复杂低效
48          * 
49          * 2、链表(单向链表):由一个链式结构把多个节点组合(包括数据和节点)连接起来形成的数据结构
50          *      存储形式:地址    0x3638FD                    0x1236FC                    0x732E2
51          *                     $123$0x1236FC                $456$0x732E2                $789$null
52          *                        ↑        ↑
53          *                 节点的数据     链接地址
54          *         使用场景1、获取元素内容为456的元素,通过从第1个节点组合开始找
55          *         使用场景2、在元素内容为456的元素后添加一个元素内容为666的元素,操作步骤如下:
56          *                 A:把元素内容为456的节点组合中链接的地址记录下来
57          *                 B:把内容为666的节点组合的地址赋给内容为456的节点组合,把456链接的地址改为666的地址
58          *                 C:把步骤A记录下来的链接地址赋给666的节点组合,让其链接
59          *     存储形式:地址    0x3638FD                    0x1236FC                0x93512                    0x732E2
60          *                     $123$0x1236FC                $456$0x93512            $666$0x732E2            $789$null
61          *                        ↑        ↑
62          *                 节点的数据     链接地址
63          *         使用场景3、删除内容为456的元素,操作步骤如下:
64          *                 A:把元素内容为456的节点组合中链接的地址记录下来
65          *                 B:把内容为456的节点组合删除掉
66          *                 C:把步骤A记录下来的链接地址赋值给内容为456的节点组合的前一个节点组合
67          *     存储形式:地址    0x3638FD                    0x732E2
68          *                     $123$0x732E2                $789$null
69          *                        ↑        ↑
70          *                 节点的数据     链接地址
71          *     
72          *         链表结构的特点:查找比较低效、增删比较高效
73          */
74         
75         // 类 ArrayList:List 接口的大小可变数组的实现。可以理解为Array(数组)形式的List
76         ArrayList arrayList = new ArrayList();
77         
78         arrayList.add("China");
79         arrayList.add("USA");
80         
81         System.out.println("ArrayList:" + arrayList);        // ArrayList:[China, USA]
82         
83         // 使用迭代器进行遍历
84         Iterator iterator = arrayList.iterator();
85         
86         while (iterator.hasNext()) {
87             String item = (String) iterator.next();
88             System.out.println(item);
89         }
90         
91         // 不使用迭代器进行遍历(使用size方法 和  get方法)
92         for (int i = 0; i < arrayList.size(); i++) {
93             String item = (String) arrayList.get(i);
94             System.out.println(item);
95         }
96     }
97 }
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Iterator;
 5 
 6 public class Sample13 {
 7     public static void main(String[] args) {
 8         ArrayList arrayList = new ArrayList();
 9 
10         arrayList.add(new Student("张三", 20));
11         arrayList.add(new Student("李四", 18));
12 
13         System.out.println("arrayList:" + arrayList);
14 
15         // 使用迭代器进行遍历
16         Iterator iterator = arrayList.iterator();
17 
18         while (iterator.hasNext()) {
19             Student item = (Student) iterator.next();
20             System.out.println(item);
21         }
22 
23         // 不使用迭代器进行遍历(使用size方法 和 get方法)
24         for (int i = 0; i < arrayList.size(); i++) {
25             Student item = (Student) arrayList.get(i);
26             System.out.println(item);
27         }
28     }
29 }
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 import java.util.ListIterator;
 6 
 7 public class Sample14 {
 8     public static void main(String[] args) {
 9         /*
10          * List自身特有的常用成员方法:
11          * 
12          * ListIterator listIterator() :返回此列表元素的列表迭代器(按适当顺序)。
13          * 
14          * ListIterator接口,继承自Iterator接口,是列表迭代器,允许程序员按任一方向遍历列表、迭代期间修改列表,并获得迭代器在列表中的当前位置。 因为继承,自然有hasNext()和next()
15          * 
16          * 1、boolean hasPrevious() :如果以逆向遍历列表,列表迭代器有多个元素,则返回 true。 2、Object previous() :返回列表中的前一个元素。
17          */
18         List list = new ArrayList();
19         list.add("大学");
20         list.add("中庸");
21         list.add("论语");
22         list.add("孟子");
23 
24         ListIterator listIterator = list.listIterator();
25 
26         // 从头至尾迭代
27         // while (listIterator.hasNext()) {
28         // String item = (String) listIterator.next();
29         // System.out.println(item);
30         // }
31 
32         System.out.println("---------------------------");
33 
34         // Object obj1 = listIterator.previous();
35         // System.out.println(obj1);
36         // Object obj2 = listIterator.previous();
37         // System.out.println(obj2);
38 
39         // 迭代器中有cursor(游标)对象,上述的操作,使得游标移动到了列表集合的最后,所以可以再向前进行迭代了
40         // 从尾至头迭代
41         while (listIterator.hasPrevious()) {
42             String item = (String) listIterator.previous();
43             System.out.println(item);
44         }
45     }
46 }
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 import java.util.ListIterator;
 6 
 7 public class Sample15 {
 8     public static void main(String[] args) {
 9         // 需求:向一个list集合中放入一些字符串,并进行遍历,便历时,如果找到"周瑜",就往集合list中添加一个字符串"诸葛亮"
10         List list = new ArrayList();
11         
12         list.add("鲁肃");
13         list.add("周瑜");
14         list.add("吕蒙");
15         
16         System.out.println("list:" + list);
17         
18 //        Iterator iterator = list.iterator();
19         
20         // java.util.ConcurrentModificationException  并发修改异常:当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。
21         // 并发:一并发生(一起发生),这里指:一边使用迭代器对list集合进行遍历,一边又向list集合中添加元素
22         // 类比:对着电风扇吹气,电风扇后面的人感觉不到吹进来的气的,因为吹的气都被电风扇的叶片击飞
23         //         也就是迭代器搞不清楚到底要迭代多少个元素,因为元素在发生着变化
24 //        while (iterator.hasNext()) {
25 //            String item = (String) iterator.next();
26 //            if (item.equals("周瑜")) {
27 //                list.add("诸葛亮");
28 //            }
29 //        }
30         
31         // 解决思路1:考虑把对list集合遍历的事情和往list集合中添加元素的事情都交给迭代器来做,自然要去看看迭代器有没有添加元素的方法
32         //        Iterator没有该方法,但是其子接口ListIterator有
33         // 类比:在电风扇的叶片上开孔,伴随着叶片的旋转向后吹气,这样后面的人应该可以感觉到吹来的气的
34         ListIterator listIterator = list.listIterator();
35         
36         while (listIterator.hasNext()) {
37             String item = (String) listIterator.next();
38             if (item.equals("周瑜")) {
39                 // void add(Object obj)将指定的元素插入列表(可选操作)。
40                 // 该元素直接插入到 next 返回的下一个元素的前面(如果有),或者 previous 返回的下一个元素之后(如果有);如果列表没有元素,那么新元素就成为列表中的唯一元素。
41                 // 新元素被插入到隐式光标前:不影响对 next 的后续调用,并且对 previous 的后续调用会返回此新元素(此调用把调用 nextIndex 或 previousIndex 所返回的值增加 1)。 
42                 listIterator.add("诸葛亮");
43                 // 下句会产生死循环么?不会,因为游标伴随着元素的添加,也向后进行了移动,也就是说不影响对 next 的后续调用
44 //                listIterator.add("周瑜");
45             }
46         }
47         
48         // 解决思路2:不依靠迭代器,也可以遍历(依靠list对象的size()方法和get()方法),
49         // 这样的遍历可以理解为依靠外力的遍历,从list集合中把元素一个一个的取出来,对list集合来说,自身有多少元素自己最清楚,再添加新的元素也没有问题
50         // 这时不存在使用迭代器去遍历,也就没有对迭代器来说,搞不清楚到底要迭代多少个元素的问题
51 //        for (int i = 0; i < list.size(); i++) {
52 //            String item = (String) list.get(i);
53 //            if (item.equals("周瑜")) {
54 //                //boolean add(Object obj) :向列表的尾部添加指定的元素(可选操作)。 
55 //                list.add("诸葛亮");
56 //            }
57 //        }
58         
59         System.out.println("list:" + list);
60     }
61 }
 1 package cn.temptation;
 2 
 3 import java.util.Enumeration;
 4 import java.util.Vector;
 5 
 6 public class Sample16 {
 7     public static void main(String[] args) {
 8         /*
 9          * Vector类:向量类,可以实现可增长的对象数组。
10          * 
11          * 从以下版本开始: JDK1.0
12          * 
13          * Vector类的常用成员方法:
14          * 1、添加功能
15          * boolean add(E e) :将指定元素添加到此向量的末尾。 
16          * void addElement(E obj) :将指定的组件添加到此向量的末尾,将其大小增加 1。
17          * 
18          * 2、获取功能
19          * E get(int index) :返回向量中指定位置的元素。 
20          * E elementAt(int index) :返回指定索引处的组件。 
21          * Enumeration<E> elements() :返回此向量的组件的枚举。 
22          * 
23          * 接口 Enumeration:枚举器
24          * 注:此接口的功能与 Iterator 接口的功能是重复的。
25          * 
26          * 接口 Iterator:迭代器
27          * 从以下版本开始: JDK1.2,作为Enumeration接口的升级版
28          * 
29          * ArrayList类,从以下版本开始: JDK1.2,作为Vector类的升级版
30          * 
31          */
32         
33         Vector vector = new Vector();
34         
35         vector.add("中国");
36         vector.addElement("美国");
37         
38         System.out.println("vector:" + vector);        // vector:[中国, 美国]
39         
40         // 遍历
41         for (int i = 0; i < vector.size(); i++) {
42             String item = (String) vector.get(i);
43             System.out.println(item);
44         }
45         
46         for (int i = 0; i < vector.size(); i++) {
47             String item = (String) vector.elementAt(i);
48             System.out.println(item);
49         }
50         
51         // 使用枚举器进行枚举
52         Enumeration enumeration = vector.elements();
53         
54         while (enumeration.hasMoreElements()) {
55             String item = (String) enumeration.nextElement();
56             System.out.println(item);
57         }
58     }
59 }
 1 package cn.temptation;
 2 
 3 import java.util.LinkedList;
 4 
 5 public class Sample17 {
 6     public static void main(String[] args) {
 7         /*
 8          * 类 LinkedList:List 接口的链接列表实现。
 9          * 
10          * LinkedList类的常用成员方法:
11          * 1、添加功能
12          * void addFirst(E e) :将指定元素插入此列表的开头。 
13          * void addLast(E e) :将指定元素添加到此列表的结尾。 
14          * 
15          * 2、获取功能
16          * E getFirst() :返回此列表的第一个元素。 
17          * E getLast() :返回此列表的最后一个元素。
18          * 
19          * 3、删除功能
20          * E removeFirst() :移除并返回此列表的第一个元素。
21          * E removeLast() :移除并返回此列表的最后一个元素。  
22          * 
23          */
24         LinkedList linkedList = new LinkedList();
25         
26         linkedList.add("中国");
27         
28         linkedList.addFirst("美国");
29         linkedList.addLast("日本");
30         
31         System.out.println("linkedList:" + linkedList);        // linkedList:[美国, 中国, 日本]
32         
33         System.out.println(linkedList.getFirst());            // 美国
34         System.out.println(linkedList.getLast());            // 日本
35         
36         System.out.println(linkedList.removeFirst());        // 美国
37         System.out.println(linkedList.removeLast());        // 日本
38         
39         System.out.println("linkedList:" + linkedList);        // linkedList:[中国]
40     }
41 }
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Iterator;
 5 
 6 public class Sample18 {
 7     public static void main(String[] args) {
 8         // 需求:使用ArrayList类的成员方法实现在ArrayList集合对象中的一系列字符串进行检查,去除重复的字符串
 9         // 例如:ArrayList:["中国","美国","日本","美国"] -----> ArrayList:["中国","美国","日本"]
10         
11         // 思路1:
12         // 1、创建一个新的容器
13         // 2、使用迭代器遍历旧的容器,获取到一个一个的元素
14         // 3、使用ArrayList类的contains方法对新容器进行检查,如果新容器中没有这个元素,就把这个元素放入到新的容器中;否则就不放入新的容器
15         // 4、这样遍历一遍旧容器中的所有元素,自然在新容器中的就是不重复的元素了
16         
17         ArrayList oldList = new ArrayList();
18         
19         oldList.add("中国");
20         oldList.add("美国");
21         oldList.add("日本");
22         oldList.add("美国");
23         oldList.add("美国");
24         oldList.add("中国");
25         
26         System.out.println("oldList:" + oldList);            // oldList:[中国, 美国, 日本, 美国]
27         
28         ArrayList newList = new ArrayList();
29         
30         Iterator iterator = oldList.iterator();
31         
32         while (iterator.hasNext()) {
33             String item = (String) iterator.next();
34             
35             if (!newList.contains(item)) {        // 新容器中不包含遍历出来的旧容器中的元素
36                 newList.add(item);
37             }
38         }
39         
40         System.out.println("newList:" + newList);            // newList:[中国, 美国, 日本]
41     }
42 }
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 
 5 public class Sample19 {
 6     public static void main(String[] args) {
 7         // 需求:使用ArrayList类的成员方法实现在ArrayList集合对象中的一系列字符串进行检查,去除重复的字符串
 8         // 例如:ArrayList:["中国","美国","日本","美国"] -----> ArrayList:["中国","美国","日本"]
 9         
10         // 思路2:
11         // 1、从第一个元素开始,把第一个元素拿出来,依次后后续的元素进行比较,如果有相同的,则删除之
12         // 2、从第二个元素开始,把第二个元素拿出来,依次后后续的元素进行比较,如果有相同的,则删除之.....
13         // n-1、从第n-1个元素开始,把第n-1个元素拿出来,依次后后续的元素进行比较,如果有相同的,则删除之
14         
15         ArrayList arrayList = new ArrayList();
16         
17         arrayList.add("中国");
18         arrayList.add("美国");
19         arrayList.add("日本");
20         arrayList.add("美国");
21         arrayList.add("美国");
22         arrayList.add("中国");
23         
24         System.out.println("arrayList:" + arrayList);        // arrayList:[中国, 美国, 日本, 美国]
25         
26 //        for (int i = 1; i < arrayList.size(); i++) {
27 //            if (arrayList.get(0).equals(arrayList.get(i))) {
28 //                arrayList.remove(i);
29 //            }
30 //        }
31 //        
32 //        for (int i = 2; i < arrayList.size(); i++) {
33 //            if (arrayList.get(1).equals(arrayList.get(i))) {
34 //                arrayList.remove(i);
35 //            }
36 //        }
37 //        
38 //        ...
39         
40         // 错误写法:
41         // 现象:如下写法会漏掉删除第三个"美国"字符串
42         // 原因:因为remove,造成了arrayList对象的长度发生了改变,进而导致元素的索引发生了变化,所以理应同步调整索引
43 //        for (int i = 0; i < arrayList.size() - 1; i++) {        // 从第一个元素到第n-1个元素都要做这样的比较
44 //            for (int j = i + 1; j < arrayList.size(); j++) {
45 //                if (arrayList.get(i).equals(arrayList.get(j))) {
46 //                    arrayList.remove(j);
47 //                }
48 //            }
49 //        }
50         
51         // 正确写法:
52         for (int i = 0; i < arrayList.size() - 1; i++) {        // 从第一个元素到第n-1个元素都要做这样的比较
53             for (int j = i + 1; j < arrayList.size(); j++) {
54                 if (arrayList.get(i).equals(arrayList.get(j))) {
55                     arrayList.remove(j);
56                     // 索引同步
57                     j--;
58                 }
59             }
60         }
61         
62         System.out.println("arrayList:" + arrayList);
63     }
64 }
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Iterator;
 5 
 6 public class Sample20 {
 7     public static void main(String[] args) {
 8         // 需求:使用ArrayList类的成员方法实现对在ArrayList集合对象中的一系列学生对象进行检查,去除重复的学生对象
 9         // 例如:ArrayList集合中存放两个  姓名为张三,年龄为20岁的学生对象,能够去除一个重复的
10         
11         // 思路1:
12         // 1、创建一个新的容器
13         // 2、使用迭代器遍历旧的容器,获取到一个一个的元素
14         // 3、使用ArrayList类的contains方法对新容器进行检查,如果新容器中没有这个元素,就把这个元素放入到新的容器中;否则就不放入新的容器
15         // 4、这样遍历一遍旧容器中的所有元素,自然在新容器中的就是不重复的元素了
16         
17         ArrayList oldList = new ArrayList();
18         
19         oldList.add(new Student("张三", 20));
20         oldList.add(new Student("李四", 22));
21         oldList.add(new Student("王五", 18));
22         oldList.add(new Student("张三", 20));
23         
24         // 遍历旧的容器
25         Object[] oldArr = oldList.toArray();
26         
27         for (int i = 0; i < oldArr.length; i++) {
28             Student temp = (Student) oldArr[i];
29             System.out.println(temp);
30         }
31         
32         System.out.println("-------------------------------------------");
33         
34         ArrayList newList = new ArrayList();
35         
36         // 遍历
37         Iterator iterator = oldList.iterator();
38         
39         while (iterator.hasNext()) {
40             Student item = (Student) iterator.next();
41             
42             // 问题:为什么去重字符串有效?去重自定义对象就无效了呢?
43             // 解决方案:查看contains方法的源码
44             if (!newList.contains(item)) {
45                 newList.add(item);
46             }
47         }
48         
49         // 遍历新的容器
50         Object[] newArr = newList.toArray();
51         
52         for (int i = 0; i < newArr.length; i++) {
53             Student temp = (Student) newArr[i];
54             System.out.println(temp);
55         }
56     }
57 }
58 // 查看ArrayList类的源码
59 // 通过分析源码,发现contains方法起作用的是if (o.equals(elementData[i]))这句代码,也就是说关键在于equals方法
60 // 回顾以前说的内容,对于引用数据类型的对象,如果自身不重写equals方法,使用的是Object类的equals方法,也就是去比较对象的地址是否相同
61 // 回想一下,字符串重写equals方法,所以字符串的equals方法比较的是字符串对象的内容
62 // 这里比较自定义对象的内容,所以考虑重写自定义对象的equals方法
63 
64 //public boolean contains(Object o) {
65 //    return indexOf(o) >= 0;
66 //}
67 
68 //public int indexOf(Object o) {
69 //    if (o == null) {
70 //        for (int i = 0; i < size; i++)
71 //            if (elementData[i]==null)
72 //                return i;
73 //    } else {
74 //        for (int i = 0; i < size; i++)
75 //            if (o.equals(elementData[i]))
76 //                return i;
77 //    }
78 //    return -1;
79 //}
 1 package cn.temptation;
 2 
 3 import java.util.ArrayList;
 4 
 5 public class Sample21 {
 6     public static void main(String[] args) {
 7         // 需求:使用ArrayList类的成员方法实现对在ArrayList集合对象中的一系列学生对象进行检查,去除重复的学生对象
 8         // 例如:ArrayList集合中存放两个  姓名为张三,年龄为20岁的学生对象,能够去除一个重复的
 9         
10         // 思路2:
11         // 1、从第一个元素开始,把第一个元素拿出来,依次后后续的元素进行比较,如果有相同的,则删除之
12         // 2、从第二个元素开始,把第二个元素拿出来,依次后后续的元素进行比较,如果有相同的,则删除之.....
13         // n-1、从第n-1个元素开始,把第n-1个元素拿出来,依次后后续的元素进行比较,如果有相同的,则删除之
14         
15         ArrayList list = new ArrayList();
16         
17         list.add(new Student("张三", 20));
18         list.add(new Student("李四", 22));
19         list.add(new Student("王五", 18));
20         list.add(new Student("张三", 20));
21         
22         // 遍历容器
23         Object[] arr = list.toArray();
24         
25         for (int i = 0; i < arr.length; i++) {
26             Student temp = (Student) arr[i];
27             System.out.println(temp);
28         }
29         
30         System.out.println("-------------------------------------------");
31         
32         for (int i = 0; i < list.size() - 1; i++) {
33             for (int j = i + 1; j < list.size(); j++) {
34                 if (list.get(i).equals(list.get(j))) {
35                     // 因为ArrayList对象的get方法获取的是Student类类型的对象,该对象已经进行了equals方法的重写
36                     list.remove(j);
37                     // 同步索引
38                     j--;
39                 }
40             }
41         }
42         
43         // 遍历容器
44         arr = list.toArray();
45         
46         for (int i = 0; i < arr.length; i++) {
47             Student temp = (Student) arr[i];
48             System.out.println(temp);
49         }
50     }
51 }
 1 package cn.temptation;
 2 
 3 public class Student {
 4     // 成员变量
 5     private String name;
 6     private int age;
 7 
 8     // 构造函数
 9     public Student() {
10         super();
11     }
12 
13     public Student(String name, int age) {
14         super();
15         this.name = name;
16         this.age = age;
17     }
18 
19     // 成员方法
20     public String getName() {
21         return name;
22     }
23 
24     public void setName(String name) {
25         this.name = name;
26     }
27 
28     public int getAge() {
29         return age;
30     }
31 
32     public void setAge(int age) {
33         this.age = age;
34     }
35     
36     @Override
37     public int hashCode() {
38         final int prime = 31;
39         int result = 1;
40         result = prime * result + age;
41         result = prime * result + ((name == null) ? 0 : name.hashCode());
42         return result;
43     }
44 
45     @Override
46     public boolean equals(Object obj) {
47         if (this == obj)
48             return true;
49         if (obj == null)
50             return false;
51         if (getClass() != obj.getClass())
52             return false;
53         Student other = (Student) obj;
54         if (age != other.age)
55             return false;
56         if (name == null) {
57             if (other.name != null)
58                 return false;
59         } else if (!name.equals(other.name))
60             return false;
61         return true;
62     }
63 
64     @Override
65     public String toString() {
66         return "学生 [姓名为:" + name + ", 年龄为:" + age + "]";
67     }
68 }
 1 package cn.temptation;
 2 
 3 import java.util.Iterator;
 4 import java.util.LinkedList;
 5 
 6 public class Sample22 {
 7     public static void main(String[] args) {
 8         // 数据结构:栈结构
 9         // 特点:先进后出、后进先出
10         // 举例:弹夹中的子弹、杯子中的水
11         
12         // 需求:运用学过的集合知识,模拟一下栈的效果
13         
14         // 思路:
15         // 因为"先进后出、后进先出",所以容器存放数据是有序的,这种有序的容器让我们选择实现List接口的集合
16         // 那么在考虑List接口的实现类ArrayList、Vector、LinkedList这三个,考虑这三个类放入数据的顺序和取出数据的顺序一致,如何实现"先进后出、后进先出"的效果?
17         // 联系到LinkedList这个实现类,可以在放入数据时玩一个花样,即放入时就排好取出时的顺序(使用一系列和first、last相关的方法)
18         
19         LinkedList linkedList = new LinkedList();
20         
21         // 下面两句效果相同
22 //        linkedList.add("中国");
23         linkedList.addFirst("中国");
24         linkedList.addFirst("美国");
25         linkedList.addFirst("日本");
26         
27         System.out.println("linkedList:" + linkedList);
28         
29         Iterator iterator = linkedList.iterator();
30         
31         while (iterator.hasNext()) {
32             String item = (String) iterator.next();
33             System.out.println(item);
34         }
35     }
36 }
 1 package cn.temptation;
 2 
 3 public class Sample23 {
 4     public static void main(String[] args) {
 5         // 需求:制作一个自定义类(Stack),实现栈的功能,有入栈功能、出栈功能、显示元素功能、判断栈中是否为空功能
 6         
 7         Stack stack = new Stack();
 8         
 9         // 入栈
10         stack.push("China");
11         stack.push("USA");
12         stack.push("Japan");
13         
14         System.out.println("入栈后:" + stack);        // 入栈后:栈 ----->[Japan, USA, China]
15         
16         // 出栈
17 //        System.out.println(stack.pop());            // Japan
18 //        System.out.println(stack.pop());            // USA
19 //        System.out.println(stack.pop());            // China
20 //        // 执行异常
21 //        System.out.println(stack.pop());
22         
23         // 重复的事情反复做很傻,且还会产生异常
24         while (!stack.isEmpty()) {
25             System.out.println(stack.pop());
26         }
27         
28         System.out.println("出栈后:" + stack);
29     }
30 }
 1 package cn.temptation;
 2 
 3 import java.util.LinkedList;
 4 
 5 /**
 6  * 自定义的栈类
 7  */
 8 public class Stack {
 9     // 成员变量
10     private LinkedList linkedList = new LinkedList();
11     
12     // 成员方法
13     
14     // 显示元素(重写toString方法)
15     @Override
16     public String toString() {
17         return "栈 ----->" + linkedList;
18     }
19     
20     // 入栈
21     public void push(Object obj) {
22         // 如果单纯只考虑push方法,可以就在方法中声明局部变量的LinkedList类型的对象,
23         // 但是不同的成员方法都会使用到LinkedList类型的对象,所以这里局部变量就应该升级为类中均可访问的成员变量
24 //        LinkedList linkedList = new LinkedList();
25         
26         linkedList.addFirst(obj);
27     }
28     
29     // 出栈
30     public Object pop() {
31         // 写法1
32         // 1、通过getFirst方法获取到集合中的第一个元素
33         // 2、通过remove方法移除集合中的第一个元素
34         // 3、返回获取到的第一个元素
35 //        Object temp = linkedList.getFirst();
36 //        linkedList.remove();
37 //        return temp;
38         
39         // 写法2
40         return linkedList.removeFirst();
41     }
42     
43     // 判断是否为空
44     public boolean isEmpty() {
45         // 写法1
46 //        return linkedList.size() == 0;
47         
48         // 写法2:继承自AbstractCollection类中的成员方法isEmpty()
49         return linkedList.isEmpty();
50     }
51 }
 1 package cn.temptation;
 2 
 3 import java.util.Stack;
 4 
 5 public class Sample24 {
 6     public static void main(String[] args) {
 7         // 类 Stack:Stack 类表示后进先出(LIFO)的对象堆栈。
 8         Stack stack = new Stack();
 9         
10         // 入栈
11         stack.push("China");
12         stack.push("USA");
13         stack.push("Japan");
14         
15         System.out.println("入栈后:" + stack);
16         
17         while (!stack.isEmpty()) {
18             System.out.println(stack.pop());
19         }
20         
21         System.out.println("出栈后:" + stack);
22     }
23 }

 

posted @ 2017-03-19 09:21  {name:"代码屠夫"}  阅读(438)  评论(1编辑  收藏  举报