这是我自己学集合的时候一些总结(This is a summary of my collection)

一、集合:了解使用集合的步骤

1.创建集合对象

2.创建元素对象

3.将元素对象添加到集合对象中

4.遍历集合

(1)list集合代码如下:

public class test {

    public static void main(String[] args) {

        //1.创建集合对象

        List list = new ArrayList();

        //2.创建元素对象

        student s1 = new student(1, “苏少有”);

        student s2 = new student(2, “苏少有2”);

        //3.将元素对象添加到集合对象中

        list.add(s1);

        list.add(s2);

        System.out.println(“list有”+list);

        //获取索引为1的元素

        Object obj = list.get(1);

        System.out.println(“索引为1的是”+obj);

        //获取集合中的元素个数

        System.out.println(“集合长度为”+list.size());

        //遍历集合

        for (int i = 0; i < list.size() ; i++) {

            Object obj2 = list.get(i);

            System.out.println(“集合有”+obj2+”数据”);

        }

    }

}

(2)增强for循环(for Each/迭代器)

*增强for循环

  for(数据类型 变量名 :数组或者集合对象) {

        //循环体,变量以及元素

  }

  //增强for循环快捷键 iter+enter

  增强for循环就是迭代器的简写模式。

*

* */

public class demo2 {

    public static void main(String[] args) {

        List list=new ArrayList();

        list.add(10);

        list.add(10);

        list.add(20);

        list.add(30);

        list.add(40);

        for(Object obj :list){

            System.out.println(obj);

        }

        System.out.println(“=========”);

        for (Object obj2 : list) {

            Integer ii=(Integer)obj2;

            System.out.println(ii);

        }

    }

}

(3)通过迭代器遍历list集合

package demo3;

import java.util.ArrayList;

import java.util.List;

import java.util.ListIterator;

/*迭代器的常用方法

     E.next();  返回迭代器的下一个元素对象.再写三层dao层查询用到resultset 遍历时while循环里面有rs.next()

     boolean hasNext(); 如果有元素可以迭代,则返回true

 注意:列表迭代器是List体系中独有的遍历方式,可以在对集合遍历的同时进行添加、删除等操作。

 但是必须通过调用列表迭代器的方法来实现。

 迭代器的使用步骤:

 1.根据集合对象获取其对象的迭代器对象

 2.判断迭代器中是否有对象

 3.如果有就获取元素

 总结:普通迭代器在遍历集合的同时不能添加或删除元素,否则会报:并发修改异常

     列表迭代器在遍历集合的同时可以添加删除集合中的元素,但必须要用列表迭代器的方法

* */

public class test {

    public static void main(String[] args) {

        //需求:测试列表迭代器

        List list = new ArrayList();

        list.add(“a”);

        list.add(“b”);

        list.add(“c”);

        //需求:判断集合中如果有字符串”b“,就在其后面添加一个新的字符串:java

        //1.根据集合对象获取列表迭代器对象

        ListIterator lit = list.listIterator();

        //2.判断迭代器中是否有对象

        while (lit.hasNext()) {

            //3.如果有就获取元素

            String s=(String)lit.next();

            if (“b”.equals(s)){

               // list.add(“java”);这样写不行,必须调用列表迭代器的方法来实现

                lit.add(“java”);

            }

            System.out.println(s);

        }

        System.out.println(“========”);

        System.out.println(list);

    }

}

(4)set集合

package demo6;

/*      单列集合(Collection)之Set集合

          特点:无序,唯一

          结论:Set集合保证所有的元素的唯一性依赖: equals()方法和hashCode()方法

 */

import java.util.HashSet;

import java.util.Iterator;

import java.util.Set;

public class test {

    public static void main(String[] args) {

        //需求:往Set集合中添加五个学生对象,然后遍历

        Set<student> set =new HashSet<student>();

        student s1=new student(“苏少有”,21);

        student s2=new student(“苏少有2”,22);

        student s3=new student(“苏少有3”,23);

        student s4=new student(“苏少有4”,24);

        student s5=new student(“苏少有”,21);

        set.add(s1);

        set.add(s2);

        set.add(s3);

        set.add(s4);

        set.add(s5);

        System.out.println(set);

        System.out.println(“———–“);

        /*打印输出语句时Set集合没有“去重”?

            因为Set集合保证元素的唯一性依赖:equals()和hashCode()两个方法

            你没有在student类中重写这两个方法,默认调用的是Object类中的这两个方法,

            而Object类中的equals()方法默认比较的是地址值是否相同

           解决方案:

              在student类中重写equals()和hashCode()方法

         */

        //通过迭代器遍历Set集合

        //1.通过集合对象获取对象的迭代器对象

        Iterator<student> it = set.iterator();

        //2.判断迭代器中是否有元素

        while (it.hasNext()){

            //3.如果有就获取元素

            student s=it.next();

            System.out.println(s);

        }

        System.out.println(“——–“);

        //增强for循环

        for (student stu : set) {

            System.out.println(stu);

        }

    }

}

student实体类

package demo6;

import java.util.Objects;

public class student {

    private String name;

    private int age;

    public student() {

    }

    public student(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 “student{” +

                “name='” + name + ‘\” +

                “, age=” + age +

                ‘}’;

    }

    @Override

    public boolean equals(Object o) {

        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        student student = (student) o;

        return age == student.age && Objects.equals(name, student.name);

    }

    @Override

    public int hashCode() {

        return Objects.hash(name, age);

    }

}

(5)Map集合

package demo7;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.Set;

/* Map集合的特点

        特点:

         双列集合,元素由键值对(Entry)构成;

         key(键)—-value(值)

        注意:

         键(key)不可以重复,值(value)可以重复

         应用:

            Map<T1,T2> map = new HashMap<>();

            解释:

               T1:表示键的数据类型

               T2:表示值的数据类型

         成员方法:

         V put(K key,V value);添加元素(键值对的形式)

         V get(Object key);根据键获取对应的值

           Set<k> keySet()     获取所有键的集合;

         遍历Map集合步骤:

         1.获取所有键的集合   keySet()

         2.遍历所有的键,获取到每一个键    迭代器 增强for

         3.根据键,获取指定值          get()

* */

public class test {

    public static void main(String[] args) {

        Map<Integer,student> map=new HashMap<Integer,student>();

        student s1=new student(“张三”,21);

        student s2=new student(“李四”,22);

        student s3=new student(“王五”,23);

        student s4=new student(“张三”,21);

        map.put(1,s1);

        map.put(2,s2);

        map.put(3,s3);

        map.put(4,s4);

        //根据键获取值

        student stu1=map.get(2);

        System.out.println(stu1);

        //打印集合

        System.out.println(map);

        System.out.println(“—–“);

        //遍历集合

        //1.获取所有键的集合   keySet()

        Set<Integer> keys = map.keySet();

        //2.遍历所有的键,获取到每一个键    迭代器 增强for

        Iterator<Integer> it = keys.iterator();

        while(it.hasNext()){

            //.根据键,获取指定值          get()

            Integer key = it.next();

            student value = map.get(key);

            System.out.println(“key:”+key+”…value:”+value);

        }

        System.out.println(“————-“);

        //增强for

        for (Integer key : keys) {

            student value = map.get(key);

            System.out.println(“key:”+key+”….value:”+value);

        }

    }

}

二.泛型

/*泛型的好处

 类型安全

 避免了类型转换

* */

public class test {

    public static void main(String[] args) {

        //需求:演示泛型

        //1.创建集合对象

        List<String> list2=new ArrayList<String>();

        //2.创建元素对象

        list2.add(“a”);

        list2.add(“b”);

        list2.add(“c”);

        //3.将元素对象添加到集合对象中

        for (String s : list2) {

            System.out.println(s);

        }

        }

}

三.Collection类的使用

/*      Collections:针对集合操作的工具类

     成员方法:

         max(Collection<T>) ;返回集合的最大元素

         sort(List<T>);      根据元素的自然顺序,将指定列表升序排列

         reverse(List<T>);   反转集合list里的元素

         shuffle(List<T>);   使用默认的随机源随机置换指定的列表

* */

public class test {

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<Integer>();

        list.add(1);

        list.add(2);

        list.add(2);

        list.add(3);

        list.add(5);

        list.add(7);

        list.add(4);

        System.out.println(“没操作前,集合里的元素有” + list);

        System.out.println(“———-“);

        //获取集合最大元素

        Integer max = Collections.max(list);

        System.out.println(“集合中的最大元素为”+max);

        System.out.println(“————“);

        //对集合进行升序排列

        Collections.sort(list);

        System.out.println(“s升序排列后集合为”+list);

        Collections.reverse(list);

        System.out.println(“反转后集合为”+list);

        Collections.shuffle(list);

        System.out.println(“随机集合元素为”+list);

    }

}

————————

1、 Sets: learn about working with sets

1. Create a collection object

2. Create element object

3. Add the element object to the collection object

4. Traverse the set

(1) The list set code is as follows:

public class test {

    public static void main(String[] args) {

// 1. Create a collection object

List list = new ArrayList();

// 2. Create element object

Student S1 = new student (1, “Su Shaoyou”);

Student S2 = new student (2, “Su Shaoyou 2”);

// 3. Add the element object to the collection object

list.add(s1);

list.add(s2);

System. Out. Println (“list yes” + list);

// Gets the element with index 1

Object obj = list.get(1);

System. Out. Println (“yes with index 1” + obj);

// Gets the number of elements in the collection

System. Out. Println (“set length is” + list. Size());

// Traversal set

for (int i = 0; i < list.size() ; i++) {

Object obj2 = list.get(i);

System. Out. Println (“set has” + obj2 + “data”);

}

}

}

(2) Enhanced for loop (for each / iterator)

*Enhanced for loop

For (data type variable name: array or collection object){

// Loop body, variables, and elements

}

// Enhanced for loop shortcut key ITER + ENTER

Enhancing the for loop is a shorthand for iterators.

*

* */

public class demo2 {

    public static void main(String[] args) {

List list=new ArrayList();

list.add(10);

list.add(10);

list.add(20);

list.add(30);

list.add(40);

for(Object obj :list){

System.out.println(obj);

}

System.out.println(“=========”);

for (Object obj2 : list) {

Integer ii=(Integer)obj2;

System.out.println(ii);

}

}

}

(3) Traversing the list collection through iterators

package demo3;

import java.util.ArrayList;

import java.util.List;

import java.util.ListIterator;

/*Common methods of iterators

E.next();   Return the next element object of the iterator. Write three more Dao layer queries. When the resultset traversal is used, there is rs.next() in the while loop

boolean hasNext(); Returns true if there are elements that can be iterated

Note: the list iterator is a unique traversal method in the list system. You can add, delete and other operations while traversing the collection.

But it must be done by calling the methods of the list iterator.

Steps for using iterators:

1. Get the iterator object of its object according to the collection object

2. Determine whether there is an object in the iterator

3. If any, get the element

Summary: ordinary iterators cannot add or delete elements while traversing the collection, otherwise: concurrent modification exception will be reported

The list iterator can add or delete elements in the collection while traversing the collection, but it must use the method of the list iterator

* */

public class test {

    public static void main(String[] args) {

// Requirements: test list iterator

List list = new ArrayList();

list.add(“a”);

list.add(“b”);

list.add(“c”);

// Requirement: if there is a string “B” in the judgment set, add a new string after it: Java

// 1. Get the list iterator object according to the collection object

        ListIterator lit = list.listIterator();

// 2. Determine whether there is an object in the iterator

while (lit.hasNext()) {

// 3. If any, get the element

String s=(String)lit.next();

if (“b”.equals(s)){

// list.add(“java”); This does not work. You must call the method of the list iterator to implement it

lit.add(“java”);

}

System.out.println(s);

}

System.out.println(“========”);

System.out.println(list);

}

}

(4) Set set

package demo6;

/*       Set set of a single column collection

Features: disorder, unique

Conclusion: the set set guarantees the uniqueness of all elements and depends on the equals () method and hashcode () method

*/

import java.util.HashSet;

import java.util.Iterator;

import java.util.Set;

public class test {

    public static void main(String[] args) {

// Requirements: add five student objects to the set, and then traverse

        Set<student> set =new HashSet<student>();

Student S1 = new student (“Su Shaoyou”, 21);

Student S2 = new student (“Su Shaoyou 2”, 22);

Student S3 = new student (“Su Shaoyou 3”, 23);

Student S4 = new student (“Su Shaoyou 4”, 24);

Student S5 = new student (“Su Shaoyou”, 21);

set.add(s1);

set.add(s2);

set.add(s3);

set.add(s4);

set.add(s5);

System.out.println(set);

System.out.println(“———–“);

/* Set set does not have “de duplication” when printing out statements?

Because the set set guarantees the uniqueness dependency of elements: the equals () and hashcode () methods

You have not overridden these two methods in the student class. By default, you call these two methods in the object class,

By default, the equals () method in the object class compares whether the address values are the same

Solution:

Override the equals () and hashcode () methods in the student class

*/

// Traversing the set collection through an iterator

// 1. Get the iterator object of the object through the collection object

        Iterator<student> it = set.iterator();

// 2. Determine whether there are elements in the iterator

while (it.hasNext()){

// 3. If any, get the element

student s=it.next();

System.out.println(s);

}

System.out.println(“——–“);

// Enhanced for loop

for (student stu : set) {

System.out.println(stu);

}

}

}

Student entity class

package demo6;

import java.util.Objects;

public class student {

    private String name;

    private int age;

    public student() {

}

    public student(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 “student{” +

“name='” + name + ‘\” +

“, age=” + age +

‘}’;

}

@ Override

    public boolean equals(Object o) {

if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        student student = (student) o;

        return age == student.age && Objects.equals(name, student.name);

}

@ Override

    public int hashCode() {

        return Objects.hash(name, age);

}

}

(5) Map collection

package demo7;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.Set;

/*Characteristics of map set

characteristic:

A two column set whose elements are composed of key value pairs (entries);

Key — value

be careful:

The key cannot be repeated, and the value can be repeated

Application:

Map< T1,T2> map = new HashMap<& gt; ();

Explanation:

T1: indicates the data type of the key

T2: represents the data type of the value

Member method:

V put(K key,V value); Add element (in the form of key value pair)

V get(Object key); Get the corresponding value according to the key

Set< k> keySet()      Get a collection of all keys;

Steps to traverse the map set:

1. Get the collection of all keys    keySet()

2. Traverse all keys and get each key     Iterator enhancement for

3. Obtain the specified value according to the key           get()

* */

public class test {

    public static void main(String[] args) {

        Map<Integer,student> map=new HashMap<Integer,student>();

Student S1 = new student (“Zhang San”, 21);

Student S2 = new student (“Li Si”, 22);

Student S3 = new student (“Wang Wu”, 23);

Student S4 = new student (“Zhang San”, 21);

map.put(1,s1);

map.put(2,s2);

map.put(3,s3);

map.put(4,s4);

// Get value according to key

student stu1=map.get(2);

System.out.println(stu1);

// Print set

System.out.println(map);

System.out.println(“—–“);

// Traversal set

// 1. Get the collection of all keys    keySet()

        Set<Integer> keys = map.keySet();

// 2. Traverse all keys and get each key     Iterator enhancement for

        Iterator<Integer> it = keys.iterator();

while(it.hasNext()){

//. Get the specified value according to the key           get()

Integer key = it.next();

student value = map.get(key);

System.out.println(“key:”+key+”…value:”+value);

}

System.out.println(“————-“);

// Enhanced for

for (Integer key : keys) {

student value = map.get(key);

System.out.println(“key:”+key+”….value:”+value);

}

}

}

2、 Generics

/*Benefits of generics

Type safety

Type conversion is avoided

* */

public class test {

    public static void main(String[] args) {

// Requirements: demonstrating generics

// 1. Create a collection object

        List<String> list2=new ArrayList<String>();

// 2. Create element object

list2.add(“a”);

list2.add(“b”);

list2.add(“c”);

// 3. Add the element object to the collection object

for (String s : list2) {

System.out.println(s);

}

}

}

3、 Use of collection class

/*       Collections: tool class for collection operations

Member method:

max(Collection<T>) ; Returns the largest element of the collection

sort(List<T>);       The specified list is arranged in ascending order according to the natural order of the elements

reverse(List<T>);    Invert the elements in the set list

shuffle(List<T>);    Randomly displaces the specified list using the default random source

* */

public class test {

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<Integer>();

list.add(1);

list.add(2);

list.add(2);

list.add(3);

list.add(5);

list.add(7);

list.add(4);

System. Out. Println (“before operation, the elements in the set have” + list);

System.out.println(“———-“);

// Gets the maximum element of the collection

        Integer max = Collections.max(list);

System. Out. Println (“the maximum element in the set is” + Max “);

System.out.println(“————“);

// Sort the set in ascending order

Collections.sort(list);

System. Out. Println (“s” set is “+ list after ascending order);

        Collections.reverse(list);

System. Out. Println (“set after inversion is” + list);

        Collections.shuffle(list);

System. Out. Println (“random set element is” + list);

}

}