Set 2 - List System and Set System

Keywords: Java ascii

List System and Set System

Article Directory

object array

  • An object array is an array that stores reference types

Use of object arrays

/*
 *Array of Objects (Reference Array): The array stores a reference type so we call it an array of objects or a reference array 
 *  The reference array stores the address value of the object, not the object 
 */
public class Demo {
	public static void main(String[] args) {
       //1. Define an array of Student types
		//int[]  arr = new int[3]
		Student[] stus=new Student[2];
		
	   //2. Assigning values to elements in an array
		//arr[0]=3;
		stus[0]=new Student("Zhang San",13); 
		stus[1]=new Student("Li Si",24);
		
	   //3. Traverse this reference array
	    /*
		 * for(int i=0;i<arr.length;i++){
		 *    System.out.println(arr[i])
		 * }
		 */
		for(int i=0;i<stus.length;i++){
			System.out.println(stus[i]);
		}
	}
}

Memory Diagram

List System

List interface introduction

An ordered collection, also known as a sequence, is described in the api.Users of this interface can precisely control where each element in the list is inserted.Users can access elements based on their integer index (position in the list) and search for elements in the list.Unlike set, lists usually allow duplicate elements.

  • List interface:

    • It is an orderly collection of elements accessed.For example, the order in which elements are stored is 11, 22, 33.Then, in the collection, the elements are stored in the order 11, 22, 33).
    • It is a collection with an index that allows you to precisely manipulate the elements in the collection (as with the index of an array).
    • Collections can have duplicate elements, and the equals method of the element compares whether or not it is a duplicate element.
  • Common subclasses of the List interface are:

    • ArrayList Collection

    • LinkedList Collection

ArrayList class

ArrayList Implementation Principle (Ideas)

  • ArrayList collection features:

    The underlying use is a reference array (Object[])

  • Expansion Thought:

When you create a new collection, the bottom layer opens up an array of 10 lengths, and calls the add() method to add elements to the array continuously. When 10 elements are added and the eleventh element is added, the array becomes full and cannot be saved. A new array of 1.5 times the original length (10+10/2) is created, and then the original elements are copied into the new array.Append the eleventh element to the end

Unique methods in ArrayList

  • Add Element Method

    add(Object e): Adds the specified element to the end of the collection

    add(int index, Object e): Specifies the index to the collection, adds the specified element, and moves the original element backward in turn

  • Delete Element Delete

remove(Object e): The specified element object is deleted from the collection and the return value is the deleted element

remove(int index): the element at the specified index is deleted from the collection, and the return value is the deleted element

  • Replace Element Method

    set(int index, Object e): Replaces the element at the specified index with the specified element, and returns the element before the replacement

  • Query Element Method

    get(int index): Gets the element at the specified index and returns it

Method demonstration:

import java.util.ArrayList;
public class Demo {
    public static void main(String[] args) {
        //list can store any data type, it must be an object
        ArrayList list = new ArrayList();
        list.add(12);//12 is an Integer object, automatically Boxed
        list.add("abc");
        list.add("def");
        list.add("abc");
        System.out.println(list);//[12, abc, def, abc]
        list.add(3,"zzz");
        System.out.println(list);//[12, abc, def, zzz, abc]
        System.out.println( list.get(1));//abc
        list.set(3,"www");
        System.out.println(list);//[12, abc, def, www, abc]
        list.remove("abc");
        System.out.println(list);//[12, abc, def, www, abc]
    }
}

ArrayList stores custom objects

public class Person {
    private int id;
    private String name;
    //Construction method
    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }
    //getter() and setter()
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    //Rewrite toString()
    @Override
    public String toString() {
        return "Person{" + "id=" + id + ", name='" + name + '\'' + '}';
    }
}


import java.util.ArrayList;
import java.util.Iterator;
public class PersonDemo {
    public static void main(String[] args) {
        ArrayList<Person> list = new ArrayList<Person>();
        list.add(new Person(01,"Zhang San"));
        list.add(new Person(02,"Li Si"));
        Iterator it = list.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
        //Person{id=1, name='Zhang San'}
        //Person{id=2, name='Li Si'}
    }
}

ArrayList features

Query elements are faster: because the bottom level is an array, the array has an index

Slow addition and deletion of elements:

Add slowly, because each add requires a large number of elements to be moved, resulting in a waste of memory resources and inefficiency

  • Reasons for adding slowly:
  • Reasons for slow deletion:

LinkedList class

LinkedList Implementation Ideas

The bottom uses a chain table, where the first element records the address values of the next element and forms a chain

LinkedList-specific methods

/*
 * LinkedList:
 *Principle:
 * LinkedList underlying use is a linked list data structure
 * LinkedList <E>member method:
 * void addFirst (E): Continuously add to the header of the list, traversing the collection from the header
    Void addLast (E): Continuously append to the end of the list of chains, traversing the collection from the beginning of the chain
 *  
 * E getFirst()//Take the first element of the chain head, but do not delete the chain head element
    E getLast()//Extract the element at the end of the chain (last), but do not delete the element at the end of the chain
    
    E removeFirst()//Take the first element of the chain head, but delete the element of the chain head
    E removeLast()//Take the element at the end of the chain, but delete the element at the end of the chain
  
 */

LinkedList features

Query elements are slower than ArrayList because the list of chains is always checked from scratch

Adding and deleting elements is faster than ArrayList: because chained lists only need to change the address values recorded in the elements, they don't need to move a large number of elements, saving memory overhead and improving efficiency

  • LinkedList Addition and Deletion Elements Principle:

Stack and Queue Data Structure

Stack: Features: Element LIFO (FIFO): Pistol Bullet Clip

Queue: Feature: Element FIFO (LIFO): Bank number

Set System

When learning the Collection interface, remember that duplicate elements can be stored in a Collection or not, so we know that duplicate elements can be stored in a List.Where do you store non-repeating elements?This is the Set interface, the collection inside it, and the elements stored are not duplicated.

Introduction to Set interface

API review of HashSet collections: This class implements the Set interface, which is supported by a hash table (actually a HashMap collection).The HashSet collection cannot guarantee the same iteration order as the element storage order.

It is characterized by: no order, no repetition

HashSet class

HashSet Basic Use

HashSet still has a collection-wide feature: add adds elements, iterator traversal, and enhanced for traversal

List of methods:

	add()		remove()		contains()		clear()		size()
  • Set out of order, all acquisitions without subscripts.So no get(i)

  • Set cannot view an element

/*
 * Set interface: no index, unique elements stored, access order is not necessarily consistent
 * HashSet: No index, guarantees unique elements, saves in different order and takes in different order
 *Member Method:
 *     Iterator<E> iterator() 
 */
import java.util.HashSet;
import java.util.Iterator;
public class Demo {
    public static void main(String[] args) {
        HashSet<String> hs=new HashSet<String>();
        hs.add("aa");
        hs.add("bb");
        hs.add("cc");
        //1. Get the iterator object
        Iterator<String> it=hs.iterator();
        //2. Loop traversal
        //iterator
        while(it.hasNext()){
            String str=it.next();
            System.out.println(str);
        }
        /*Enhance for
        for(String str : hs){
            System.out.println(str);
        }
        */
    }
}
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
//Set Collection Filter String
public class Demo {
    //Scanner Input String Reduplication
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter a string:");
        String str = input.nextLine();
        //1.String-->Char[]
        char[] cs = str.toCharArray();
        //2.Set Collection
        Set<Character> set = new HashSet<>();
        //3. Place each character in a Set
        for (int i = 0 ; i < cs.length ; i++){
            set.add(cs[i]);//add() self-filtered duplicates
        }
        System.out.println(set);
    }
}

add() determines whether an object is duplicated, and relies on contains()

The contains() base relies on equals(), and overriding equals() resolves the problem of object duplication in the Set of Sets.

Hash algorithm

  • Hash algorithm is faster than normal lookup
  • Hash algorithm guarantees uniqueness

HashSet Store String Guarantee Uniqueness Principle

The string stored in a HashSet depends on two methods, one hashCode() method and the other equals() method. Note that both methods come from the Object class, but String overrides them. The hashCode() method of a String class no longer returns a memory address value like the hashCode() method of an Object class, but calculates the ASCII code value of a character in a string based on an algorithm, and the equ of a String classThe als() method is to compare the contents of two strings

import java.util.HashSet;
/*
 * HashSet Unique Principle
 *   First call the hashCode() method to compare the hash values of the elements
 *   If the added element hash value is different from the hash value of the element in the collection, save it directly
 *   If the added element hash value is the same as that of the element in the collection
 *      Call the equals() method to compare the contents of two elements
 *         equals()Returns true, indicating that the two elements have the same content, are considered duplicates and do not exist
 *         equals()Returns false, indicating that the contents of the two elements are different.
 *   Object The original hashCode() in the class returns the memory address value
 */
public class Demo {
    public static void main(String[] args){
        HashSet<String> hs=new HashSet<String>();
        hs.add("ab");//Save directly when the first ab is saved
        hs.add("ab");//When the second ab is saved, the hashCode() method is called first to get the hash values of the two elements, and the comparison finds the same
        //When the equals method is called, ab. euqlas ("ab")//true, the second AB does not exist

        hs.add("bc");//When saving bc, call hashCode() method first to get two element hash values
        //Compare found to be different, save directly    
        System.out.println(hs);//[ab, bc]
        System.out.println("ab".hashCode());//3105
        System.out.println("bc".hashCode());//3137
    }
}

HashSet Access Custom Object Guarantee Uniqueness Principle

When we store custom objects with the same name and age, we cannot weight them with HashSet:

Because Person takes advantage of the hashCode method inherited from the Object class, it gets an element's address value comparison

Each Person is a new Person with a different address value

public class Person /*extends Object*/ {
    private String name;
    private int age;

    public Person(String name, int age) {
        super();
        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;
    }

}


import java.util.HashSet;
/*
 * Storing custom objects using HashSet
 */
public class PersonDemo {
    public static void main(String[] args) {
        //1. Create a HashSet collection
        HashSet<Person> hs=new HashSet<Person>();

        //2. Create 3 Person objects
        /*Person p=new Person("Zhang San ", 12);
         *hs.add(p);
         */
        hs.add(new Person("Zhang San",12));//Anonymous object
        hs.add(new Person("Zhang San",12));//Call the hashCode() method to get a hash (memory address value) to compare
        //The hash value of the second Person object is different from that of the first Person
        //The second Person is saved directly
        hs.add(new Person("King Five",16));

        //3. Traverse HashSet collections
        for(Person p : hs){
            System.out.println(p.getName()+" "+p.getAge());
        }
        //Zhang San 12
        //Zhang San 12
        //Wang Wu16
    }
}

We try to override (rewrite) the original hashCode and equals methods to ensure that people of the same age are filtered out

public class Person /*extends Object*/ {
    private String name;
    private int age;

    public Person(String name, int age) {
        super();
        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;
    }
    /*In overriding hashCode(), we typically use all the properties of this class to generate hash values*/
	/*@Override
	public int hashCode() {
		 //return 10;
		return name.hashCode() + age;
	}*/
    /*
     *return 10,Make all elements have the same hash value and all elements have to be called
     *equals()compare
     * For new Person (Zhang San, 12) there is also a new Person (Wang Wu, 16)
     *  Both names and ages are different, so there is no need to call equals again
     */

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }


    /*
     * euqual Method overrides are the same as before
     *  If two people have the same name and age, consider them the same person, and return true
     *  Returns false if two people have at least one different name and age
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
}

import java.util.HashSet;
public class PersonDemo {
    public static void main(String[] args) {
        // 1. Create a HashSet collection
        HashSet<Person> hs = new HashSet<Person>();

        // 2. Create 3 Person objects
        Person p1=new Person("Zhang San", 12);
        Person p2=new Person("Zhang San", 12);
        Person p3=new Person("King Five", 16);
        hs.add(p1);//p1 Direct Save In
        hs.add(p2);//To save p2, you need to call the hashCode() method to get the hash value of p1,p2
        //Hash value is the same, need to compare equals(), return true, think the same element, does not exist
        hs.add(p3);//To save p3, you need to call the hashCode() method to get the hash value of p3,p1
        //Instead, save p3 directly

        System.out.println(p1.hashCode());//776222
        System.out.println(p2.hashCode());// 776222
        System.out.println(p3.hashCode());// 938522

        // 3. Traverse HashSet collections
        for (Person p : hs) {
            System.out.println(p.getName() + " " + p.getAge());
        }
        //Wang Wu16
        //Zhang San 12
    }
}
Twenty-one original articles were published. Approved 0. Visits 189
Private letter follow

Posted by neuromancer on Tue, 11 Feb 2020 19:47:20 -0800