Java Notes-Collection Class

collection class

1 Why use collection classes?

A collection class is a class used to store multiple data.
We learned about arrays in the Java foundation, and data can store multiple data. Why use a collection?

1.2 Characteristics of arrays

  1. used to store multiple data
  2. The data types of the data in the array are the same
  3. The length of the array is fixed
  4. The operation of the array requires the developer to define the relevant operation algorithm

1.3 Characteristics of collection classes

  1. Multiple data can be stored in the collection class
  2. Any type of the type of data stored in the collection class (the internal type is Object type, so any type can be stored)
  3. The length of the collection class is variable
  4. Common operation methods on such collections are provided in the collection class, and developers can implement common operations on collections through these methods

The collection class is not a class, but a collective name for a set of interfaces and classes

2 Class structure of collection class in Java

Collection classes in Java are divided into two types of collections according to different storage methods

  1. 线性Collection based on Collection interface

    There are two sub-interfaces under the Collection interface, corresponding to different linear collections

    1. Features of the List interface

      (1). An ordered set (the order of entering into the set is the same as the order of taking it out)
      (2). A set that can store duplicate data

      • Implementation class of List interface:
        ①.ArrayList
        ②.LinkedList
        ③.Vector
    2. Set interface

      (1). Unordered collection (the order of elements in the collection is not guaranteed)
      (2). Collections that do not allow duplicate data

      • Implementation class of Set interface:
        ①.HashSet
        ②.TreeSet
  2. key-valueA collection of mapping pairs based on the Map interface

3 Use of the ArrayList class based on the List interface

The bottom layer of ArrayList is implemented based on dynamic array

3.1 Features of ArrayList

  1. When using ArrayList, it is more efficient to find the elements in it. The array has subscripts, which can be directly locked to an element through subscripts.

  2. ArrayList is inefficient when inserting or removing elements (shifting in memory)

3.2 Common APIs of ArrayList

  1. Create an ArrayList object

    //创建ArrayList集合类对象
    ArrayList arrayList = new ArrayList();
    
  2. add(element): Append an element to the end of the ArrayList

    //向ArrayList的尾部追加元素
         arrayList.add("aaa");
         arrayList.add(20);
         arrayList.add('a');
         arrayList.add(true);
      arrayList.add(20.5);
    
  3. add(index, element): Insert an element at a certain position in the collection

    //向ArrayList某个位置插入元素
         arrayList.add(2,"str")
    
  4. set(index,element) : replace an element in the collection

    //更改ArrayList替换位置的元素
         arrayList.set(2,"set")
    
  5. contains(element): Check whether the collection has the specified element

    //检查ArrayList中是否含有指定元素
         arrayList.contains("set")
    
  6. isEmpty(): Check if the container is empty

    arrayList.isEmpty()
    
  7. get(index): Get the element corresponding to the subscript according to the subscript, and return the Object type by default (convert the specific type according to your own needs)

    //根据下标获得一个元素
         String str= (String) arrayList.get(0);
         System.out.println(str);
    
  8. remove(element|index):

    If the parameter is an object type, it will be removed according to the content; if the parameter is a basic type of int type, it will be removed according to the subscript

         //移除元素
         arrayList.remove("aaa");
         System.out.println(arrayList);
         //如果参数为int类型,则根据下标移除,如果要移除的内容为整数则需要使用Integer类型删除
         arrayList.remove(new Integer(3));
         System.out.println(arrayList);
    
  9. addAll(): set union operation

            ArrayList<String> arrayList=new ArrayList<>();
            arrayList.add("1");
            arrayList.add("2");
            ArrayList<String> arrayList1=new ArrayList<>();
            arrayList1.add("我是一");
            arrayList1.add("我是二");
            arrayList.addAll(arrayList1);
    
  10. retainAll(): set intersection operation

        ArrayList<String> arrayList2=new ArrayList<>();
        arrayList2.add("1");
        arrayList2.add("我是二");
        arrayList2.add("我是一");
        ArrayList<String> arrayList3=new ArrayList<>();
        arrayList3.add("我是一");
        arrayList3.add("我是二");
        boolean flag= arrayList2.retainAll(arrayList3);//判断是否交集成功
  1. removeAll(): set difference operation

            ArrayList<String> arrayList4=new ArrayList<>();
            arrayList4.add("1");
            arrayList4.add("我是二");
            arrayList4.add("我是一");
            ArrayList<String> arrayList5=new ArrayList<>();
            arrayList5.add("我是一");
            arrayList5.add("我是二");
            boolean flag1=arrayList4.removeAll(arrayList5);
    
  2. Iterate through all elements in the ArrayList collection

    //遍历List集合中的所有元素
            //使用传统for循环遍历
            for(int i=0;i<arrayList.size();i++){
          
          
            Object obj = arrayList.get(i);
            System.out.println(obj);
            }
            System.out.println("---------------");
            //使用for循环加强版遍历
            for(Object obj : arrayList){
          
          
            System.out.println(obj);
            }
            System.out.println("---------------");
            //用迭代器遍历
            Iterator  iterator=arrayList.iterator();
            while(iterator.hasNext()
                System.out.println(iterator.next())
            }
            //使用list集合中的foreach方法进行遍历
            arrayList.forEach(System.out::println);
    

4 Implementation class Vector based on List interface

4.1 Features of Vector

1. The bottom layer of Vector is also implemented based on dynamic array
2. The operations provided in Vector are basically the same as ArrayList

4.2 The difference between ArrayList and Vector

  1. The same point: the bottom layer of ArrayList and Vector are both implemented based on dynamic arrays, and provide similar APIs
  2. Differences:
    (1) ArrayList creates an array with a length of 0 by default, while Vector creates an array with a length of 10
    (2) Vector is thread-safe, while ArrayList is not thread-safe. It is recommended to use Vector under concurrent conditions.
    We can pass External means to make ArrayList thread-safe

5 Vector's subclass Stark

The Stark stack container, a subclass of Vector, implements a last-in, first-out stack

5.1 Features of Stark

last in first out

5.2 Stark common APIs

  1. Create a Stark object

     //实例化栈容器
        Stack<String> stack=new Stack<>();
    
  2. push() into the stack, push the stack

    //入栈
            stack.push("one");
            stack.push("two");
            stack.push("three");
    
  3. pop() pops the stack, pops the stack (deletes the object at the top of the stack and returns its value)

    //出栈  
    //获取栈容器元素
            System.out.println(stack.pop());
            System.out.println(stack.pop());
            System.out.println(stack.pop()); 
    
  4. empty() checks if the stack container is empty

    //检查栈容器是否为空 
            System.out.println(stack.empty());
    
  5. peek() reads the top element of the stack

    //查看栈顶元素
            System.out.println(stack.peek());
    
  6. search() returns the position of the stack element in the container

    System.out.println(stack.search("one"));
    

5.3 Stark use cases

  1. Judging element symmetry

    String str=“… {…[…(…)…]…}…(…)…[…]…” ;

    public class Test01 {
          
          
        public static void main(String[] args) {
          
          
            String str="... {.....[....(....)...]....}..(....)..[...]..." ;
            Stack<String> stack=new Stack<>();
            //假设修正法
            boolean flag=true;//假设是匹配的
            //拆分字符串获取字符
            for (int i=0;i<str.length();i++){
          
          
                char chars=str.charAt(i);
                if (chars == '['){
          
          
                    stack.push("]");
                }
                if (chars =='{'){
          
          
                    stack.push("}");
                }
                if (chars =='('){
          
          
                    stack.push(")");
                }
                //判断符号是否匹配
                if (chars =='}'||chars==']'||chars==')'){
          
          
                    if (stack.empty()){
          
          
                        flag=false;
                        break;
                    }
                    String str1= stack.pop();
                    if (str1.charAt(0)!=chars){
          
          
                        flag=false;
                        break;
                    }
                }
            }
            if (!stack.empty()){
          
          
                flag=false;
            }
            System.out.println(flag);
        }
    }
    

6 Implementation class LinkedList based on List interface

The bottom layer of LinkedList is based on linked list implementation

6.1 Features of LinkedList

1. High efficiency when inserting or deleting elements
2. Low efficiency when querying and traversing elements

6.2 Common APIs of LinkedList

  1. add(element): add at the end
  2. addFirst(element): the first insert
  3. addLast(element): tail insertion
  4. add(index,element): Insert an element at the specified subscript position
  5. push(element): into the stack
  6. pop(): out of the stack
  7. toArray(): convert the list to an array

7 Implementation class HashSet based on Set interface

7.1 Features of HashSet

  1. The bottom layer is based on the implementation of the Map collection
  2. Cannot store duplicate data
  3. The elements in the set are not in guaranteed order
  4. The Set collection cannot directly obtain an element from the collection
  5. The Set collection has no subscript

7.2 Common APIs of HashSet

1.add(element): Add an element to the collection
2.iterator(): Traverse all elements in the collection

//遍历集合中元素
        Iterator<String> iterator = hashSet.iterator();
        //循环遍历集合中的每个元素
        while(iterator.hasNext()){
    
    //检测集合中是否存在要迭代的数据,true表示存在
            String str = iterator.next();//获取一个元素
            System.out.println(str);
        }

3. Through the foreach loop to traverse all the elements in the collection

//使用foreach遍历集合中的所有元素
        for(String str : hashSet){
    
    
            System.out.println(str);
        }

4. Use the foreach method to traverse the elements in the collection

//通过foreach方法遍历集合中的所有元素
        hashSet.forEach(System.out::println);

8 TreeSet implementation based on Set interface

TreeSet is a Set collection based on a tree structure, which can be sorted and is called a sortable Set collection

8.1 Characteristics of TreeSet Collection

1. TreeSet is an ordered Set collection
2. Duplicate data cannot be stored
in TreeSet 3. The elements stored in TreeSet must be sortable elements (objects that implement the comparator interface), if the stored elements are not sortable element will report an exception (ClassCastException)

9 Map collection based on key-value (key-value pair)

The elements stored in the Map collection are a key corresponding to a value

9.1 Characteristics of the Map collection

1. The key is not allowed to be repeated. By default, the key is of Object type and can store any type of data. 2. The
value is allowed to be repeated. By default, the value is of Object type and can store any type of data.
3. Null is allowed in the Map key (can only appear once) and null value

9.2 Implementation class HashMap based on Map interface

Duplicate keys are not allowed to be stored in HashMap. If the newly added key already exists, the new value will be used to replace the original value.

9.3 Common APIs of HashMap

1.put(key,val):Add a pair of key-value to the Map collection
2.get(key):Get the corresponding value according to the key
3.remove(key):Remove an element in the Map collection according to the
key4 .size(): Get the number of elements in the collection
5.keySet(): Get all the keys in the Map collection and return a包含所有key的set集合

        //获取hashmap中所有元素
        System.out.println(hashMap.keySet());
        for (String map :hashMap.keySet()){
    
    
            System.out.println(map+"<--------->"+hashMap.get(map));
        }
    }
}

6.values(): Obtain all values ​​in the Map collection and return a Collection collection
7.entrySet(): Obtain the Entry collection object of each element in the Map collection and return the Set collection

for (Map.Entry<String,String> entry : map.entrySet()){
    
    
            System.out.println(entry.getKey()+"<--->"+entry.getValue());
        }

The key in the Map collection cannot be repeated. If you want to add a new element to the Map, how does the Map collection determine whether the element exists in the collection?

10 TreeMap implementation class based on Map interface

TreeMap, like TreeSet, is a sortable collection.
TreeMap is sorted according to the key.
The elements (keys) entering the TreeMap must be sortable elements (keys).

11 Additional Knowledge Points

  • Collections tool class

    • Collections commonly used api
      void sort(List) sorts the elements in the container
      void shuffle(List) randomly sorts the elements in the List
      void reverse(List) sorts the elements in the List in reverse order
      void fill(List,Object) uses a specific object Rewrite the entire container
      int binarySerach(List,Object) binary search
      addAll(Collection,element...): add multiple elements to the collection at one time
  • equals method


== is also used to judge whether two objects are equal: the equals method used to judge whether two objects are the same object is used to judge whether the values ​​of two objects are equal

        String s1 = "abc";
        String s2 = "abc";
        //s1和s2两个变量都指向“abc”字符串对象,他们两个是同一个对象
        System.out.println(s1 == s2);
        /**
         * Java中每次使用new关键字创建对象时,在JVM的堆区都会自动创建一个新对象
         * 只不过两个对象的值都是"abc"字符串
         * 这两个对象不是同一个对象,但他们的值是相等
         * 所以“==”的结果为false,他们两个不是同一个对象
         * 如果要判断两个对象的值是否相等使用equals方法
         */
        String str = new String("abc");
        String str1 = new String("abc");
        System.out.println(str == str1);//false
        System.out.println(str.equals(str1));

The equals method exists in any object. This method is defined in the Object class. They are positioned by default as

 public boolean equals(Object obj) {
    
    
        return this == obj;
    }

As can be seen from the source code in the Object class, the default definition of the equals method is to judge whether two objects are the same object. So in order to be able to judge
whether the values ​​​​of the two objects are equal, we will rewrite this method in the entity class we define The method
String overrides the equals method, and most classes in the JDK override this method...

  • hashCode method

The hashCode method exists in any class. This method is also defined in the Object class. The
hashCode method is used to obtain the hash code of the memory address corresponding to the current object.
If the hashes of the two objects are equal, it means that the current two objects must be
The developer of the same object (by default) can rewrite the hashCode according to actual needs, and the hashCode of different objects may be equal after rewriting

In development, the equals method and the hashCode method are generally rewritten to change their default behavior

  • How does the Map collection determine whether the key of the newly added element exists in the collection?

1. First judge whether the hashCode is equal. If the hashCode is not equal, it is considered that there is no identical object, and the new element is directly added to the map collection. 2. If the value of the hashCode is equal, it is
impossible to determine whether the same object exists, and then continue to judge equals method, if the return value of equals is true, it is considered that there is an equal element
Replace the original element with a new element, if the equals judgment is unequal, it is considered that there is no identical object, and the new element is directly added to the map collection

  • Comparator interface

The comparator is used to define the comparison rules. With the comparison rules, the data can be sorted according to the comparison rules.
There are two ways to define the comparison rules in Java:

(1) Implement the Comparable interface: Comparable is under the java.lang package
- Comparable is used to implement the default comparison rules of objects, and there is only one default comparison rule
- there is a compareTo method in Comparable, which is used to define the comparison rules
- the return of the method The value is a positive integer indicating that the current object is greater than the comparison object
- the return value of the method is equal to 0 and the two objects are equal
- the return value of the method is a negative integer indicating that the current object is smaller than the comparison object

@Override
    public int compareTo(User user) {
    
    

        return this.userId - user.getUserId();
    }

(2) Implement the Comparator interface: Comparator is under the java.util package
- Comparator is used to define extended comparison rules for objects, and multiple can be defined
- Comparator interface has a method compare(obj1, obj2)
- method for defining comparison rules The return value is a positive integer indicating that obj1 is greater than obj2
- the return value of the method is equal to 0 and the two objects are equal
- the return value of the method is a negative integer indicating that obj1 is less than obj2

/**
 * 使用内部类定义扩展规则
 * 1.根据积分升序排序
 */
    static class sortByScoreASC implements Comparator<User>{
    
    


    @Override
    public int compare(User user1, User user2) {
    
    
        return user1.getUserScore() - user2.getUserScore();
    }
}

/**
 * 2.根据积分降序排序
 */

static class sortByScoreDESC implements Comparator<User>{
    
    


    @Override
    public int compare(User user1, User user2) {
    
    
        return user2.getUserScore() - user1.getUserScore();
    }
}


    /**
     * 2.根据学号降序排序
     */

    static class sortByUserIdDESC implements Comparator<User>{
    
    


        @Override
        public int compare(User user1, User user2) {
    
    
            return user2.getUserId() - user1.getUserId();
        }
    }
    
    //调用
// TreeSet<User> users = new TreeSet<>();//使用user对象中的默认排序规则进行排序
       //使用User内定义的内部类指定排序规则
    // TreeSet<User> users = new TreeSet<>(new User.sortByUserIdDESC());
       //使用匿名内部类定义排序规则
    TreeSet<User> users = new TreeSet<>(new Comparator<User>() {
    
    
       //使用匿名内部类实现比较器接口
       @Override
       public int compare(User user1, User user2) {
    
    
          return user1.getRegDate().compareTo(user2.getRegDate());
       }
    });
  • transient keyword

Add the keyword transient before the property that does not need to be serialized. When serializing the object, this property will not be serialized.

1) Once the variable is modified by transient, the variable will no longer be part of object persistence, and the variable content cannot be accessed after serialization.

2) The transient keyword can only modify variables, not methods and classes. Note that local variables cannot be modified by the transient keyword. If the variable is a user-defined class variable, the class needs to implement the Serializable interface.

3) Variables modified by the transient keyword can no longer be serialized, and a static variable cannot be serialized regardless of whether it is modified by transient.

  • native keyword

Java cannot directly access the operating system and the bottom layer of the hardware. It needs to use the native keyword to control the bottom layer. This requires the support of a lower-level language. This is the role of native


  • Learning comes from Xi'an Jiazhong training

Guess you like

Origin blog.csdn.net/woschengxuyuan/article/details/126262111