List, Set, data structure, Collections

List, Set, data structure, Collections data structure Common data structures Common structures of data storage incl...
List, Set, data structure, Collections
Four Set interface
V Collections

List, Set, data structure, Collections

data structure

Common data structures
  • Common structures of data storage include:
    • Stack, queue, array, linked list and red black tree
Stack
  • Stack: stack, also known as stack, is a linear table with limited operation. Its limitation is that it is only allowed to insert and delete at one end of the target, and it is not allowed to add, find and delete at any other location.

Simply put: with this structure, the access to elements has the following characteristics

  • First in, then out (that is, the elements saved in can only be taken out after the elements behind it are taken out in turn). For example, when a bullet is pressed into a magazine, the first one is below, and the second one is above. When shooting, the bullet on the top will be ejected first, and then the bullet on the bottom will be ejected.

  • The entrance and exit of the stack are the top positions of the stack.

  • Two nouns need to be noted:

    • Stack pressing: it is the storage element. That is, the elements are stored at the top of the stack, and the existing elements in the stack move one position towards the bottom of the stack.
    • Pop stack: take elements. That is, take out the top position element of the stack, and the existing elements in the stack move one position towards the top of the stack in turn.
queue
  • Queue: queue, or queue for short, is a kind of linear table with limited operation just like stack. Its limitation is that it is only allowed to insert at one end of the table and delete at the other end of the table.

Simply put, with the structure of the set, the access to elements has the following characteristics:

  • First in, first out (that is, the elements stored in can only be taken out after the elements in front of it are taken out in turn). For example, when a small train passes through a cave, it goes first at the head and then goes in at the end; it comes out first at the head and then comes out at the end.
  • The entrance and exit of the queue occupy one side respectively. For example, in the following figure, the left side is the entrance and the right side is the exit.
array
  • Array: array is an ordered sequence of elements. Array is a continuous space in memory where elements are stored. It's like a row of rental houses. There are 100 rooms. From 001 to 100, each room has a fixed number. You can quickly find the renter through the number.

Simply put, with the structure of the set, the access to elements has the following characteristics:

  • Find elements quickly: through index, you can quickly access the elements in the specified location

  • Slow addition and deletion of elements

  • Add element at specified index position: create a new array, store the specified new element at the specified index position, and copy the original array element to the corresponding index position of the new array according to the index.

  • **Delete element at specified index position: * * a new array needs to be created. Copy the original array element to the corresponding index position of the new array according to the index. The specified index position element in the original array will not be copied to the new array.

Linked list
  • Linked list: a linked list consists of a series of nodes (each element in the list is called a node), which can be generated dynamically at runtime.
    • Each node consists of two parts:
      • One is the data domain where data elements are stored
      • The other is the pointer field that stores the address of the next node.
        We often say that the chain list structure has one-way list and two-way list, and the following is one-way list.

Simply put, with the structure of the set, the access to elements has the following characteristics:

  • Multiple nodes are connected by address. For example, many people hold hands, each person uses his right hand to hold the next person's left hand, and so on, so that many people are connected.

  • Slow to find an element: to find an element, you need to find the specified element backward through the connected nodes

  • Fast addition and deletion of elements:

    • Add element: just modify the address of the next element.
    • Delete element: you only need to modify the address of the next element.
Red black tree
  • binary tree is an ordered tree with no more than 2 nodes.

    • A simple understanding is a structure similar to the tree in our life, except that each node can only have two child nodes at most.

    • A binary tree is a tree structure in which each node has at most two subtrees. The top is called root node, and the two sides are called "left subtree" and "right subtree".

As shown in the picture:

A kind of interesting binary tree is called red black tree. Red black tree itself is a binary search tree. After inserting nodes, the tree is still a binary search tree. This means that the key values of the tree are still ordered.

  • Red black tree constraints:
  1. Nodes can be red or black

  2. The root node is black

  3. Leaf nodes (especially empty nodes) are black

  4. The children of each red node are black

  5. The number of black nodes in all paths from any node to each leaf node is the same

  • Characteristics of the red black tree:

The speed is very fast, approaching the balance tree, and the minimum and maximum times of finding leaf elements are not more than twice

Two List sets

Several common subclasses in collection

  • java.util.List collection
  • java.util.Set collection
List interface introduction

java.util.List interface inherits from Collection interface, which is an important branch of single column Collection. It is customary to call the objects that implement List interface List Collection. Duplicate elements are allowed in the List Collection. All elements are stored in a linear way, and the specified elements in the Collection can be accessed through the index in the program. In addition, the List set also has a feature that the elements are ordered, that is, the storage order of the elements is consistent with the removal order.

List interface features:

  1. It is a collection of elements with orderly access. For example, the order in which the elements are stored is 11, 22, 33. Then, in the collection, the storage of elements is completed in the order of 11, 22, 33).
  2. It is a collection with index, through which the elements in the collection can be operated precisely (the same reason as the index of the array).
  3. There can be duplicate elements in the collection. Use the equals method of the element to compare whether it is a duplicate element.

Note: we have learned the subclass java.util.ArrayList class of the List interface in the basic class. The methods in this class are all defined from the List.

Common methods in List interface

As a sub interface of Collection collection, List not only inherits all methods in Collection interface, but also adds some unique methods to operate Collection according to element index, as follows:

  • public void add(int index, E element): adds the specified element to the specified location in the collection.
  • public E get(int index): returns the element at the specified location in the collection.
  • public E remove(int index): remove the element at the specified location in the list, and return the removed element.
  • public E set(int index, E element): replace the element at the specified location in the set with the specified element, and return the element before the value is updated.

List collection specific methods are all index related

public class ListDemo { public static void main(String[] args) { // Create List collection object List<String> list = new ArrayList<String>(); // Add specified element to tail list.add("Tutu"); list.add("Xiaomei"); list.add("Unhappy"); System.out.println(list); // add(int index,String s) to the specified location list.add(1,"Mindless"); System.out.println(list); // String remove(int index) delete the specified location element and return the deleted element // Delete element with index position 2 System.out.println("Delete element with index position 2"); System.out.println(list.remove(2)); System.out.println(list); // String set(int index,String s) // Replace the element at the specified location // Modify the specified location element list.set(0, "San Mao"); System.out.println(list); // String get(int index) gets the specified location element // Used to traverse with the size() method for(int i = 0;i<list.size();i++){ System.out.println(list.get(i)); } //You can also use the enhanced for for (String string : list) { System.out.println(string); } } }

Subclasses of three lists

ArrayList collection
  • The most commonly used functions in daily development are querying data and traversing data, so ArrayList is the most commonly used collection.
LinkedList collection

The structure of java.util.LinkedList collection data store is linked list structure. A collection that facilitates the addition and deletion of elements.

LinkedList is a two-way linked list


**The first operation method * *, just understand it

  • public void addFirst(E e): inserts the specified element at the beginning of this list.
  • public void addLast(E e): adds the specified element to the end of this list.
  • public E getFirst(): returns the first element of this list.
  • public E getLast(): returns the last element of this list.
  • public E removeFirst(): removes and returns the first element of this list.
  • public E removeLast(): removes and returns the last element of this list.
  • public E pop(): pops an element from the stack represented by this list.
  • Public void push (e e e): push elements into the stack represented by this list.
  • public boolean isEmpty(): returns true if the list does not contain elements.

Method demonstration:

public class LinkedListDemo { public static void main(String[] args) { LinkedList<String> link = new LinkedList<String>(); //Additive elements link.addFirst("abc1"); link.addFirst("abc2"); link.addFirst("abc3"); System.out.println(link); // Get elements System.out.println(link.getFirst()); System.out.println(link.getLast()); // Delete elements System.out.println(link.removeFirst()); System.out.println(link.removeLast()); while (!link.isEmpty()) { //Judge whether the set is empty System.out.println(link.pop()); //Top of stack element in pop-up collection } System.out.println(link); } }

Four Set interface

  • The java.util.Set interface, like the java.util.List interface, also inherits from the Collection interface
  • It is basically the same as the method in the Collection interface. It does not extend the function of the Collection interface, but is more strict than the Collection interface.
  • Different from the List interface, the elements in the Set interface are unordered, and the stored elements will not be duplicated with some rules.

Set set has multiple subclasses

  • java.util.HashSet
  • java.util.LinkedHashSet.

tips:Set sets can extract elements in the following ways: iterator, enhanced for.

Introduction to HashSet collection
  • java.util.HashSet is an implementation class of Set interface. The elements it stores are not repeatable, and all elements are out of order (i.e. access order is inconsistent).

  • HashSet is based on the hash value of the object to determine the storage location of the elements in the collection, so it has good access and search performance. The way to guarantee element uniqueness depends on: hashCode and equals methods.

Phenomenon of using Set set Set storage:

public class HashSetDemo { public static void main(String[] args) { //Create Set set HashSet<String> set = new HashSet<String>(); //Additive elements set.add(new String("cba")); set.add("abc"); set.add("bac"); set.add("cba"); //ergodic for (String name : set) { System.out.println(name); } } }

The output is as follows, indicating that duplicate elements cannot be stored in the collection:

cba abc bac

Note: according to the results, we found that the string "cba" only stores one, that is, the duplicate element set set is not stored.

The structure (hash table) in which the HashSet collection stores data
  • Hashtable
    Hash table is implemented by array + linked list + red black tree (JDK 1.8 adds red black tree part)
  • Hash table stored process
HashSet stores custom type elements

When storing custom type elements in a HashSet, you need to override the hashCode and equals methods in the object and establish your own comparison method to ensure that the objects in the HashSet set are unique

Create a custom Student class

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 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); } }
public class HashSetDemo2 { public static void main(String[] args) { //Create a collection object the collection stores Student type objects HashSet<Student> stuSet = new HashSet<Student>(); //storage Student stu = new Student("Yu Qian", 43); stuSet.add(stu); stuSet.add(new Student("Guo Degang", 44)); stuSet.add(new Student("Yu Qian", 43)); stuSet.add(new Student("Guo Kirin", 23)); stuSet.add(stu); for (Student stu2 : stuSet) { System.out.println(stu2); } } } //Result: Student [name=Guo Degang, age=44] Student [name=Yu Qian, age=43] Student [name=Guo Kirin, age=23]
LinkedHashSet

Under the HashSet, there is a subclass java.util.LinkedHashSet, which is a data storage structure composed of linked list and hash table.

public class LinkedHashSetDemo { public static void main(String[] args) { Set<String> set = new LinkedHashSet<String>(); set.add("bbb"); set.add("aaa"); set.add("abc"); set.add("bbc"); Iterator<String> it = set.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } } //Result: bbb aaa abc bbc
Variable parameters

After JDK 1.5, if a method needs to accept multiple parameters and multiple parameter types are the same, it can be simplified to the following format:

Modifier return value type method name (parameter type... Parameter name) {}

This writing is equivalent to

Modifier return value type method name (parameter type [] parameter name) {}

The latter must pass array when calling, the former can pass array directly

  • After JDK 1.5. Simplified operations have emerged When it is used on parameters, it is called variable parameter.

    It also represents an array, but when calling this method with variable parameters, the elements in the array are directly passed as actual parameters without creating the array
    In fact, the compiled class file first encapsulates these elements into an array for passing. These actions are automatically completed when compiling. Class files.

public class ChangeArgs { public static void main(String[] args) { int[] arr = { 1, 4, 62, 431, 2 }; int sum = getSum(arr); System.out.println(sum); // 6 7 2 12 2121 // Find the sum of these elements 6 7 2 12 2121 int sum2 = getSum(6, 7, 2, 12, 2121); System.out.println(sum2); } /* * Complete the original writing method of summing all elements of the array public static int getSum(int[] arr){ int sum = 0; for(int a : arr){ sum += a; } return sum; } */ //Variable parameter writing public static int getSum(int... arr) { int sum = 0; for (int a : arr) { sum += a; } return sum; } }

Be careful:

  1. The above add method can only exist in one class. Because of the uncertainty of the call
  2. When writing a method, the method has multiple parameters, including variable parameters, which must be written at the end of the parameter list.

V Collections

Common functions

  • java.utils.Collections is a collection tool class used to operate on collections. Some methods are as follows:
  • Public static < T > Boolean addall (collection < T > C, t... Elements): add some elements to the collection.
  • Public static void shuffle (list <? > list) scramble order: scramble the collection order.
  • Public static < T > void sort (list < T > list): sorts the elements in the collection according to the default rules.
  • Public static < T > void sort (list < T > list, comparator <? Super T >): sorts the elements in the collection according to the specified rules.
public class CollectionsDemo { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); //Original writing method //list.add(12); //list.add(14); //list.add(15); //list.add(1000); //Using tool classes to add elements to a collection Collections.addAll(list, 5, 222, 1,2); System.out.println(list); //Ranking method Collections.sort(list); System.out.println(list); } } //Result: [5, 222, 1, 2] [1, 2, 5, 222]

The above sets are arranged in [default] order

  • Public static < T > void sort (list < T > list, comparator <? Super T >): sort the elements in the set according to the specified rule
Comparator comparator

Public static < T > void sort (list < T > list): sorts the elements in the collection according to the default rule.

The string type is stored.

public class CollectionsDemo2 { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("cba"); list.add("aba"); list.add("sba"); list.add("nba"); //Ranking method Collections.sort(list); System.out.println(list); } }

Result:

[aba, cba, nba, sba]

How are default rules defined

  • Sorting is to compare the size of two objects. In JAVA, there are two ways to realize the comparison
  1. Using java.lang.compatible interface to implement
  2. The java.util.Comparator interface is complete.
  • The public static < T > void sort (list < T > list) method is used to complete the sorting. In fact, the sorted type needs to realize the function of comparison through the Comparable interface. The String type is as follows:
public final class String implements java.io.Serializable, Comparable<String>, CharSequence {

The String class implements this interface and completes the definition of comparison rules. However, this kind of rules is written to death. For example, if I want strings to be arranged in descending order of the first character, then I need to modify the source code of the String. This is impossible. It can be used at this time

Public static < T > void sort (list < T > list, comparator <? Super T >) method is flexibly completed. This involves the comparator interface, which is located in the java.util package. Sorting is one of the functions that the comparator can achieve. This interface represents a comparator, which has comparability! As the name implies, sorting is done. Generally speaking, it is necessary to compare the first and the second of two objects. Then, the method of comparison is as follows:

  • public int compare(String o1, String o2): compare the order of its two parameters.

    There are three results of comparison between two objects: greater than, equal to, and less than.

    If you want to sort in ascending order,
    If o1 is less than o2, return (negative number), equal return 0, 01 is greater than 02 return (positive number)
    If you want to sort in descending order
    If o1 is less than o2, return (positive), equal return 0, 01 is greater than 02 return (negative)

public class CollectionsDemo3 { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("cba"); list.add("aba"); list.add("sba"); list.add("nba"); //Sort by descending the first word Collections.sort(list, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o2.charAt(0) - o1.charAt(0); } }); System.out.println(list); } }

Result

[sba, nba, cba, aba]
The difference between Comparable and Comparator.

Comparable: forces an overall ordering of the objects of each class that implements it. This sort is called the natural sort of class, and the compareTo method of class is called its natural compare method. compareTo() can only be implemented once in a class. You can't often modify the code of the class to implement the sorting you want. The list of objects (and arrays) that implement this interface can be automatically sorted by Collections.sort (and Arrays.sort). Objects can be used as keys in ordered mappings or elements in ordered collections without specifying a comparer.

Comparator forces an overall sort of an object. You can pass comparators to sort methods such as Collections.sort or Arrays.sort, allowing precise control over the sort order. You can also use comparator to control the order of some data structures, such as ordered set s or ordered mappings, or to provide sorting for collections of objects that do not have a natural order.

2.4 practice

Create a student class and store it in the ArrayList collection to complete the specified sorting operation.

Student initial class

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 + '}'; } }

Test class:

public class Demo { public static void main(String[] args) { // Create four student objects to store in the collection ArrayList<Student> list = new ArrayList<Student>(); list.add(new Student("rose",18)); list.add(new Student("jack",16)); list.add(new Student("abc",16)); list.add(new Student("ace",17)); list.add(new Student("mark",16)); /* Ask students to rank in ascending order by age */ // Collections.sort(list); / / the element type in the list must implement the comparator compatible interface for (Student student : list) { System.out.println(student); } } }

The program reported an error when calling the Collections.sort() method.

Reason: if you want the elements in the collection to be sorted, you must implement the comparator compatible interface.

Then an implementation of the Student class is completed, as follows:

public class Student implements Comparable<Student>{ .... @Override public int compareTo(Student o) { return this.age-o.age;//Ascending order } }

Test again, result

Student{name='jack', age=16} Student{name='abc', age=16} Student{name='mark', age=16} Student{name='ace', age=17} Student{name='rose', age=18}
extend

If you want to define rules independently when you use them, you can use collections.sort (list list, comparator C) to define rules by yourself:

Collections.sort(list, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o2.getAge()-o1.getAge();//In descending order of student's age } });

Result:

Student Student Student Student Student
ning96 42 original articles published, praised 0, 877 visitors Private letter follow

12 February 2020, 05:19 | Views: 5871

Add new comment

For adding a comment, please log in
or create account

0 comments