JavaSE Review Foundation Consolidation

Posted by TheBentinel.com on Mon, 06 Dec 2021 19:39:41 +0100

Day 7: Single Collection List   Set
Talk about the array and compare it with the set before reviewing it
Array: Can be seen as a container for storing data. (a contiguous block of memory is created in memory)
Characteristic:
1. Fixed length
2. Store fixed data types, store the same type of data, can store basic data types can also store reference data types.
3. Arrays have default values
 
Collection: is also a container for storing data (and opens up a space in memory)
Collections (containers): Used to store and retrieve data, by storing and retrieving data in different ways, the collection can be subdivided.
Why do we have collections?
Because the length of the array is fixed and immutable. The length of the collection is not fixed, variable, and more flexible to use.
Features of a collection:
1. The length is variable.
2. Only objects can be stored
3. There is no default
 
Collection is simply the general name of a container that can only store objects and has variable length, and such containers can be subdivided by different ways of storage and retrieval.
1. collection
The collection collection collection collection (parent interface) has a list interface and a set interface. Below the list, there are ArrayList classes (implementation classes) and linkList classes. Below the set, there are HshSet classes (implementation classes) and TreeSet classes.
Note: We learn from the top-level interface of the architecture, using its specific implementation class.
 
List features:
1. Order (the order in which data is stored and retrieved is consistent)
2. Indexed
3. Elements can be repeated
The features of set:
1. Unordered (the order in which data is stored and retrieved is inconsistent) 2. No index
3. Elements cannot be repeated
 
1.1 Collection common methods:

boolean add(Object e): Add elements to a collection

Boolean addAll (Collection): Add elements to the collection

void clear(): Empty all elements in the collection

boolean contains(Object o): Determines if an element is included in a collection

boolean isEmpty(): Determines if an element in a collection is empty

boolean remove(Object o): Delete an element based on its content

Example:

/*      boolean add(Object e): Add elements to a collection
        boolean addAll(Collection e): Add elements to a collection
        void clear():Empty all elements in the collection
        boolean contains(Object o):Determine if an element is included in a collection
        boolean isEmpty():Determine if an element in a set is empty
        boolean remove(Object o):Delete an element based on its content
        int size():Get the length of the collection
        Object[] toArray():Ability to convert a collection into an array and store the elements in the collection into an array*/
        //Establish collection Object Polymorphism: References to parent classes point to objects of subclasses
        Collection c=new ArrayList();
        //Call parent class collection Inside, but implemented in subclasses ArrayList in
        //1 boolean add(Object e): Add elements to a collection
//        c.add(1);//Here is a process packaging class for auto-packing
        c.add("zhangsan");
        c.add("lisi");
        c.add("wangwu");
        c.add("wangwu");
        //Can repeat why ArrayList Can collections repeat when adding data? because add()The return value of is always true
        System.out.println(c);//The order of storage and retrieval is the same output:[zhangsan, lisi, wangwu]

   //Create a collection
        Collection c=new ArrayList();
        //Add data to a collection
        c.add("Zhang San");
        c.add("Li Si");
        c.add("King Five");
//        method1(c);
        // Object[] toArray():Ability to convert a collection into an array and store the elements in the collection into an array
        Object[] arr = c.toArray();
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }

    }

    private static void method1(Collection c) {
        Collection c1=new ArrayList();
//        boolean addAll(Collection e): Adding elements to a collection is equivalent to copying a collection
        c1.addAll(c);
        System.out.println(c1);
//        void clear():Empty all elements in the collection
//         c.clear(); []  empty
//        boolean contains(Object o):Determine if an element is included in a collection
        System.out.println(c.contains("Zhao Six"));//false
        System.out.println(c.contains("Li Si"));//true
//        boolean isEmpty():Determine if an element in a set is empty
        System.out.println(c.isEmpty());//false
//        boolean remove(Object o):Delete an element based on its content
        System.out.println("Successfully deleted:"+c.remove("Zhang San"));//true
        System.out.println(c);
//        int size():Get the length of the collection
        System.out.println(c.size());

    }
 
1.2 Iterator
Tools for traversing collections
    There are many collections available in java that store elements differently. We want to take out the elements from these collections in a common way.
Collection collection elements are generally obtained by determining if there are any elements in the collection before taking them out. If there are, take this element out, continue to make judgments, and then take it out if there are any. Always take out all the elements in the collection. This method of removal is termed iteration.
This way of taking elements is described in the collection in the Iterator interface. Common methods for the Iterator interface are as follows
hasNext() method: Determines if there are elements in the set that can be iterated over
Next() method: Used to return the next element of an iteration and move the pointer one bit backward.
remove (): Delete the element currently being fetched
  Example:
package com.swlz.collection;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class CollectionDemo4 {
    public static void main(String[] args) {
        //Create Collection Object
        List c=new ArrayList();
        //Add data
        c.add("Zhang San");
        c.add("Li Si");
        c.add("King Five");
        c.add("Zhao Six");
        c.add("Qian Qi");
        //To solve the problem of using Colletion The concurrent modification exception problem that occurs with the set iterator, which we want to use List Iterators for sets
        /*ListIterator<E> listIterator()
          Returns the list iterator for this list element in the appropriate order. */
        ListIterator lit = c.listIterator();
        //Traverse Set
        while(lit.hasNext()){
            String s1=(String)lit.next();
            if(s1.equals("Qian Qi")){
                //Use List The iterator of a collection resolves concurrent modification exceptions to added elements
                //A deleted concurrent modification exception can also be resolved, but only the condition itself can be deleted
               lit.add("Next-door King");
//                lit.remove();//Delete Qian Seven
            }

        }
        System.out.println(c);

    }
}

 

1.3 Foreach: Traversing through a set
//Foreach Enhancement for - The bottom level is the iterator Iterator in the collection collection set.
//So you can't change the number of elements in a collection, we're generally used to iterate through the collection directly
Grammar Format
foreach (object data type object: collection name){
Circulatory body
}
 
 
Interview Question: What is the difference between ArrayList and LinkedList?
1.ArrayList has arrays at the bottom, which are fast and slow to query.
2.LinkedLIst has a chain table at the bottom. Queries are slow and add or delete quickly
 
List Collection Common Methods
  void add(int index, E element): Add an element to the index index position
E get(int index): Get elements from index
E remove(int index): Delete elements according to index
E set(int index, E element): Set the element at the index position to element
Example:
package com.swlz.collection;

import java.util.ArrayList;
import java.util.List;

public class ListDemo1 {
    public static void main(String[] args) {
       /* void add(int index, E element) :Add element to index position
        E get(int index) :Get elements from index
        E remove(int index) :Delete elements according to index
        E set(int index, E element):Set the element at index position to elementmodification*/
        List list=new ArrayList();
        //Add elements to index On index position
        list.add("Jan");
        list.add("plum");
        list.add("Peng");
        System.out.println(list);
        //  E get(int index) :according to index Index Get Elements
        System.out.println(list.get(0));
        System.out.println(list.get(1));
        System.out.println(list.get(2));
        // E remove(int index) :according to index Index Delete Element
        list.remove(0);
        System.out.println(list);
        //E set(int index, E element):take index The element at the index position is set to element  modify
        list.set(0,"Zhang San");//Change the element with index 0 to Zhang San



    }
}
1.4 LinkedList Collection Common Methods

  LinkedList uses a chain table structure at the bottom, so it increases or decreases quickly and queries are slower than ArrayList

Void addFirst (E): Add an element to the head of a chain table

  Void addLast (E): Add an element to the end of the list of chains

  E getFirst(): Get the element of the chain head without deleting the element

  E getLast(): Gets the element at the end of the chain without deleting it

  E removeFirst(): Returns the element of the chain head and deletes the element of the chain head

  E removeLast(): Returns the element at the end of the chain and deletes the element at the end of the chain

1. Code

import java.util.LinkedList;

/*

 * Common subclasses of List:

 * ArrayList

 * The bottom level is the array structure, queries are fast, increases or decreases

 * LinkedList

 * The underlying structure is a chain table, queries are slow and add or delete quickly

 *

 * How do I choose to use different collections?

 * Use ArrayList if you have more queries and fewer additions or deletions

 * If fewer queries, more additions and deletions, use LinkedList

 * If you don't know what to use, use ArrayList

 *

 * LinkedList features:

 * void addFirst(E e)  

 * void addLast(E e)

  E getFirst()  

  E getLast()  

  E removeFirst()

  E removeLast()

 *

 */

public class LinkedListDemo {

public static void main(String[] args) {

LinkedList list = new LinkedList();

list.add("hello");

list.add("world");

//void addFirst(E)  : Add element to position with index 0

  // Void addLast (E): Adds an element to the location indexed as size()-1

list.addFirst("java");

list.addLast("android");

 

  // E getFirst()  : Get the element with index 0

  // E getLast()  : Gets the element with index size()-1

//System.out.println(list.getFirst());

//System.out.println(list.getLast());

 

  // E removeFirst(): Delete element with index 0 and return

  // E removeLast(): Delete the element with index size()-1 and return

System.out.println(list.removeFirst());

System.out.println(list.removeLast());

System.out.println(list);

}

}

 
1.5 Collections Tool Class
Collections Tool Class - A tool class designed to manipulate List collections
What is a tool class? Tool classes encapsulate a number of methods that are provided for use with the corresponding data.
Methods in tool classes are generally static and are easy to call directly from the class name
Example:
package com.swlz.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsDemo1 {
    public static void main(String[] args) {
        //Collections Tool class---Is dedicated to operation List Tool classes for collections
        //What is a tool class?---Tool classes encapsulate a number of methods that are provided for use with the corresponding data.
        // Methods in tool classes are generally static and are easy to call directly from the class name
       /* static int  binarySearch(List list, Object key) Use binary search to find the index position of a specified element in a specified list
          static void copy(List dest, List src) :Is to overwrite the data in the source list to the target column (copy the set)
        * static void fill(List list, Object obj) :Populate all elements of the specified list with the specified object
          //static void reverse(List list)  :Reversal
        * //static void shuffle(List list):Silly, random substitution
        * //static void  sort(List<T> list) :Sort elements in the list in their natural order
        * //static void swap(List list, int i, int j) :Interchange the positions of two indexes in a specified list*/
        List list=new ArrayList();
        list.add(5);
        list.add(3);
        list.add(7);
        list.add(2);
        list.add(9);
        int i = Collections.binarySearch(list, 7);//Use binary search to find the index position of a specified element in a specified list
        System.out.println(i);//index Is 2


    }
}
 
1.6 set collection (interface)
Characteristic:
1. The order in which data (elements) are stored in a collection is not consistent with the order in which they are removed (out of order)
2. No index
3. Elements stored in a collection cannot be repeated
Why can't set collection elements be repeated?
Because set sets are map's put methods, the actual principle of put methods is to compare the hashes of our objects in putval().
HashSet collection (bottom is hash table)
Use of HashSet Collection
1 case:
 public class HashSetDemo2 {
public static void main(String[] args) {
//Create a collection object
HashSet<Student> hs = new HashSet<Student>();
//Create Element Object
Student s = new Student("zhangsan",18);
Student s2 = new Student("lisi",19);
Student s3 = new Student("lisi",19);
//Add Element Object
hs.add(s);
hs.add(s2);
hs.add(s3);
//Traverse collection objects
for (Student student : hs) {
System.out.println(student);
 
1.6.1 HashSet Uniqueness Principle
    Rule: New elements added to the HashSet collection will be compared to elements already in the collection
        First compare the hash values (each element calls hashCode() to produce a hash value) If the newly added element has a different hash value from an existing element in the collection, the newly added element is stored in the collection If the newly added element has the same hash value as an existing element in the collection, then call equals(Object obj) to compare if the equals(Object obj) method returns true, Explains that if the newly added element has the same attribute value as an element already in the collection, then the newly added element does not reside in the collection and if the equals(Object obj) method returns false,   Indicates that the attribute values of the newly added element are different from those of the existing element in the collection, then the newly added element is stored in the collection
/*
 * Use HashSet to store custom objects and traverse them
 * Discover by looking at the source code:
 * HashSet's add() method first compares hash values with each element in the current set and the newly added element.
 * If hash values are different, add new elements directly
 * If hash values are the same, compare address values or use the equals method to compare
 * If the comparison results are the same, it is considered duplicate and not added
 * Add if all comparison results are different
 */
public class HashSetDemo2 {
public static void main(String[] args) {
//Create a collection object
HashSet<Student> hs = new HashSet<Student>();
//Create Element Object
Student s = new Student("zhangsan",18);
Student s2 = new Student("lisi",19);
Student s3 = new Student("lisi",19);
//Add Element Object
hs.add(s);
hs.add(s2);
hs.add(s3);
//Traverse collection objects
for (Student student : hs) {
System.out.println(student);
}
}
}
class Student {
String name;
int age;
public Student(String name,int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
 
@Override
public boolean equals(Object obj) {
//System.out.println("-------------------");
Student s = (Student)obj;// Transition down to get subclass-specific members
//Compare if age is equal, if not return false
if(this.age != s.age) {
return false;
}
//Compare if names are equal or return false if they are not
if(!this.name.equals(s.name)) {
return false;
}
//Returns true by default, indicating that the two students are equal
return true;
}
@Override
public int hashCode() {
return 1;
}
}
Summary: The optimization of hashcode method:
Because when the hash values of the objects are different, the objects can be stored directly in the collection without calling equals()
But there is a need to do weight removal and sometimes call equals() to compare the contents of the object
When all hashes are set to the same value, equals() is called many times to compare the contents of the object.
The method call digests time and reduces program execution efficiency.
So you need to optimize the hashcode method
The hash value of the field is treated as the hash value of the object. When the contents of the two objects are inconsistent, the hash values of the fields must be different. Therefore, the objects can be stored directly without calling equals(). When the contents of the two objects are identical, the hash values of the fields are the same, and the equals() method needs to be called once to compare the contents for weight removal. This reduces calls to the equals() method.
1.hashCode method optimization:
    If the hashCode() method returns a fixed value, then it is less efficient to call the equals(Object obj) method to compare each newly added element
    By simply letting elements with different attribute values produce different hash values, you can no longer call the equals method to compare productivity
 
1.7 TreeSet (bottom is tree)
TreeSet feature: You can sort elements in a Set collection.
 
Today's learning experience: The singleton collection in today's learning collection must understand itself. Then there are many ways to understand it. You need to knock once more, knock more, master the core methods, and have an impression. Don't be intermittent on the way to study, but insist. Last sentence: Persist is victory!
If you see this blog's buddies, it's helpful for you. Please give them a compliment.

Topics: Java JavaSE