编程知识 cdmana.com

My 20th day of learning Java in Shanghai Le byte

Java aggregate ( On )

Java The set in is a tool class , Any number of objects with common properties can be stored

  • Why use sets , Instead of arrays ?
    – Storage 20 Student information ( Array )
    – Store product information ( aggregate )
  • Application scenarios
  • There is no way to predict the amount of data stored
  • Also store data with a one-to-one relationship
  • We need to add or delete data
  • Data duplication problem

Java Collection framework architecture

 Insert picture description here

List( list )

  • List It's an ordered and repeatable set of elements , It's called a sequence
  • List It can precisely control the insertion position of each element , Or delete the element in a certain position
  • List The two main implementation classes of are ArrayList and LinkedList

ArrayList

  • ArrayList The bottom layer is implemented by arrays
  • Dynamic growth , To meet the needs of the application
  • Inserting or deleting at the end of the list is very effective
  • Better for finding and updating elements
  • ArrayList The elements in can be null

The set belongs to java.util Bag ( For specific information, you can find API file , I'll list them all )
Collection

 Insert picture description here

List

 Insert picture description here

ArrayList

 Insert picture description here

 Insert picture description here

Case a

  • use ArrayList Store the name of the programming language , And the output
  • The name includes “ Java” 、“C”、“C++”、“Go” and “Swift”
  • Specifically used add()、size()、remove(int index)、remove(Object o) Method
package com.sh.set;

import java.util.ArrayList;

import java.util.List;

public class ListDemo1 {

public static void main(String[] args) {

// use ArrayList Store the name of the programming language , And the output

List list=new ArrayList();

list.add("Java");

list.add("C");

list.add("C++");

list.add("Go");

list.add("swift");

// The number of elements in the output list

System.out.println(" The number of elements in the list is :"+list.size());

// Traverse output all programming languages

System.out.println("**");

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

System.out.print(list.get(i)+",");

}

// Remove from the list C++

System.out.println();

list.remove(2);

// list.remove("C++");

System.out.println("**");

System.out.println(" remove C++ The following list elements are :");

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

System.out.print(list.get(i)+",");

}

}

}

  • Storage methods in memory

 Insert picture description here

  • Running results

 Insert picture description here

Case 2 ( Announcement management )

  • demand
    – The addition and display of announcements
    – Insert an announcement at the specified location
    – Delete announcement
    – Modify bulletin
  • Announcement class properties
    – Number id
    – title title
    – founder creator
    – Creation time createTime
  • Announcement class method
    – Construction method
    – Methods to get and set property values
  • The method used
    – add(int index, E element) Inserts the specified element at the specified location in the list
    – remove(int index) Remove the element at the specified location in the list
    – set(int index, E element) Replace the element at the specified location in the list with the specified element
package com.sh.set;

import java.util.Date;

public class Notice {

private int id;//ID

private String title;// title

private String creator;// founder

private Date createTime;// Creation time

public Notice(int id, String title, String creator, Date createTime) {

super();

this.id = id;

this.title = title;

this.creator = creator;

this.createTime = createTime;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

public String getCreator() {

return creator;

}

public void setCreator(String creator) {

this.creator = creator;

}

public Date getCreateTime() {

return createTime;

}

public void setCreateTime(Date createTime) {

this.createTime = createTime;

}

}

// Test class

package com.sh.set;

import java.util.ArrayList;

import java.util.Date;

public class NoticeTest {

public static void main(String[] args) {

// establish Notice Class object , Generate three announcements

Notice notice1 = new Notice(1, " Welcome to learning net !", " Administrators ", new Date());

Notice notice2 = new Notice(2, " Please submit your homework on time !", " teacher ", new Date());

Notice notice3 = new Notice(3, " Attendance notice !", " teacher ", new Date());

// Add announcement

ArrayList noticeList = new ArrayList();

noticeList.add(notice1);

noticeList.add(notice2);

noticeList.add(notice3);

// Show the announcement

System.out.println(" The content of the announcement is :");

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

      System.out.println(i + 1 + ":" + ((Notice) (noticeList.get(i))).getTitle());

}

      System.out.println(" Time :"+((Notice)(noticeList.get(1))).getCreateTime());

System.out.println("**");

// Add a new announcement after the first announcement

Notice notice4 = new Notice(4, " The online editor is ready to use !", " Administrators ", new Date());

noticeList.add(1, notice4);

// Show the announcement

System.out.println(" The content of the announcement is :");

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

System.out.println(i + 1 + ":" + ((Notice) (noticeList.get(i))).getTitle());

}

System.out.println("**");

// Delete the post of submitting homework on time

noticeList.remove(2);

// Show the announcement

System.out.println(" The content after deleting the announcement is :");

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

System.out.println(i + 1 + ":" + ((Notice) (noticeList.get(i))).getTitle());

}

// Change the second announcement to :Java The online editor is ready to use !

System.out.println("**");

// Amend the second announcement title Value

notice4.setTitle("Java The online editor is ready to use !");

noticeList.set(1, notice4);

System.out.println(" The content of the revised announcement is :");

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

System.out.println(i + 1 + ":" + ((Notice) (noticeList.get(i))).getTitle());

}

}

}

Running results

LinkedList

  • And ArrayList equally ,LinkedList Also sort by index position , But its elements are two-way linked
  • Suitable for quick insertion and deletion of elements
  • LinkedList Realization List and Queue Two interfaces

Construction method

 Insert picture description here

 Insert picture description here

 Insert picture description here

Case a : Use LinkedList Manage strings

package com.sh.set;

import java.util.LinkedList;

public class LinkedListDemo1 {

public static void main(String[] args) {

LinkedList<String> list = new LinkedList<String>();

// Add data to the linked list

list.add("apple");

list.add("pear");

// Add data to the beginning of the linked list

list.addFirst("banana");

// Add data to the end of the linked list

list.addLast("grape");

// Add data at the specified location , The first parameter is zero index value , from 0 Start

list.add(2, "orange");

// Display all the data in the linked list

System.out.println(list);

// Determine whether the list contains the specified element , And output the corresponding results

boolean flag = list.contains("grape");

if (flag) {

System.out.println("grape eureka !");

} else {

System.out.println("grape Did not find !");

}

// return index The value is 3 And output

System.out.println("index The value is 3 The data is :" + list.get(3));

// Returns the first element

System.out.println(" The first element is :" + list.getFirst());

// Return to the last element

System.out.println(" The last element is :" + list.getLast());

}

}

  • Running results

 Insert picture description here

Case 2 : Use LinkedList Manage custom classes

Student class

package com.sh.set;

public class Student {

private String stuNum;

private String stuName;

private int age;

public Student(String stuNum, String stuName, int age) {

this.stuNum = stuNum;

this.stuName = stuName;

this.age = age;

}

public String getStuNum() {

return stuNum;

}

public void setStuNum(String stuNum) {

this.stuNum = stuNum;

}

public String getStuName() {

return stuName;

}

public void setStuName(String stuName) {

this.stuName = stuName;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

@Override

public String toString() {

return " [ Student number :" + stuNum + ", full name :" + stuName + ", Age :" + age + "]";

}

}

LinkedListDemo2 class

package com.sh.set;

import java.util.LinkedList;

public class LinkedListDemo2 {

public static void main(String[] args) {

LinkedList<Student> stuList = new LinkedList<Student>();

Student stu1 = new Student("001", "Mike", 18);

Student stu2 = new Student("002", "Jack", 20);

Student stu3 = new Student("003", "Lucy", 19);

// Add students to the linked list , Use push complete

// LinkedList Realization List Interface at the same time , It has also been realized. Queue Interface

// push and pop Aimed at Queue To add and retrieve data

stuList.push(stu1);

stuList.push(stu2);

stuList.push(stu3);

System.out.println(" The linked list is :" + stuList);

// Pop up an element , Here you can think of a linked list as a container , First add the data to the linked list and then pop up ,

// According to the principle of "first in, then out"

System.out.println(" The pop-up data is :" + stuList.pop());

System.out.println(" call pop() The linked list after the method is :n" + stuList);

// peek() Method does not remove the element

System.out.println(" call peek() The data of the method is :" + stuList.peek());

System.out.println(" call peek() The linked list after the method is :n" + stuList);

// Call again pop() Method , Discovery call pop() After the method, the data is removed from the linked list , and peek() No way

System.out.println(" Call again pop() Method " + stuList.pop());

System.out.println(" Call again pop() The linked list after the method is :n" + stuList);

// Add the element again in the linked list

stuList.push(stu2);

stuList.push(stu3);

System.out.println(" The linked list after adding elements again is :n" + stuList);

// call poll() Method

System.out.println(" call poll() Method output element " + stuList.poll());

// call poll() Method will get the element and delete the element from the linked list at the same time

System.out.println(" call poll() The linked list after the method is :n" + stuList);

}

}

  • Running results

 Insert picture description here

Set

  • Set It's a collection of elements that are out of order and can't be repeated , It's called a set

HashSet

  • HashSet yes Set An important implementation class of , It's called a hash set
  • HashSet The elements in are out of order and cannot be repeated
  • HashSet Only one is allowed in null Elements
  • It has good access and search performance

TreeSet( You can see API file )

Set

 Insert picture description here

HashSet

 Insert picture description here

Iterator( iterator )

  • Iterator Interface can traverse various collection elements in a unified way
  • hasNext() Method to detect if there is another element in the collection
  • next() Method returns the next element in the collection

 Insert picture description here

  • Iterator traverses the flow
    – Implementation method for Circulation and while loop

 Insert picture description here

 Insert picture description here

 Insert picture description here

 Insert picture description here

Case a

  • HashSet Store multiple English words for color , And the output
  • Words include “blue”、“red”、“black”、" yllow" and “white”
  • Use add() Method iterator Iterator
package com.sh.set;

import java.util.HashSet;

import java.util.Iterator;

import java.util.Set;

public class WordDemo {

public static void main(String[] args) {

// Add words to English HashSet in

Set set = new HashSet();

// Add elements to the collection

set.add("blue");

set.add("red");

set.add("black");

set.add("yellow");

set.add("white");

// Show the contents of the collection

System.out.println(" The elements in the collection are :");

Iterator it = set.iterator();

// Iterate through iterators and output elements

while (it.hasNext()) {

System.out.print(it.next() + "   ");

}

// for(Iterator<Set> it1=set.iterator();it1.hasNext();) {

//        System.out.println(it1.next());

//        }

System.out.println();

// Insert a new word into the collection

// set.add("green");

set.add("white");

it = set.iterator();

// Iterate through iterators and output elements

System.out.println("");

System.out.println(" The output after inserting the repeating element is :");

while (it.hasNext()) {

System.out.print(it.next() + "   ");

}

// Insert the failure , But there is no error

}

}

Case 2 ( Pet cat information management )

  • demand
    – Add and display cat information
    – Find the information of a pet cat and output
    – Modify cat information
    – Delete cat information
  • attribute
    – name name
    – Age month
    – Varieties species
  • Method
    – Construction method
    – Methods to get and set property values
    – Other methods hashCode and equals
    – To find the way

hashCode and equals

 Insert picture description here

Hash table and general storage sequence ( Hash table can improve the speed of data search )

 Insert picture description here

The hash table is divided into three parts ( Multiple ) Area to store data , What data is put in which area There is a rule (hashCode)

 Insert picture description here

 Insert picture description here

  • To determine which area belongs to hashCode Method
  • Determine whether a region object is what we are looking for , use equals Method
package com.sh.set;

public class Cat {

private String name; // name

private int month; // Age

private String species;// Varieties

// Construction method

public Cat(String name, int month, String species) {

super();

this.name = name;

this.month = month;

this.species = species;

}

    //getter And setter Method

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getMonth() {

return month;

}

public void setMonth(int month) {

this.month = month;

}

public String getSpecies() {

return species;

}

public void setSpecies(String species) {

this.species = species;

}

@Override

public String toString() {

return "[ full name :" + name + ", Age :" + month + ", Varieties :" + species + "]";

}

@Override

public int hashCode() {

final int prime = 31;

int result = 1;

result = prime * result + month;

result = prime * result + ((name == null) ? 0 : name.hashCode());

result = prime * result + ((species == null) ? 0 : species.hashCode());

return result;

}

@Override

public boolean equals(Object obj) {

// Judge whether the objects are equal , Equal returns true, You don't have to continue comparing attributes

if(this==obj)

return true;

// Judge obj Whether it is Cat Class object

if(obj.getClass()==Cat.class){

Cat cat=(Cat)obj;

return cat.getName().equals(name)&&(cat.getMonth()==month)&&(cat.getSpecies().equals(species));

}

return false;

}

}

// Test class

package com.sh.set;

import java.util.HashSet;

import java.util.Iterator;

import java.util.Set;

public class CatTest {

public static void main(String[] args) {

// Define the pet cat object

Cat huahua = new Cat(" tearful ", 12, " British short haired cat ");

Cat fanfan = new Cat(" Every one of them ", 3, " Chinese country cat ");

// Put the pet cat object in HashSet in

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

set.add(huahua);

set.add(fanfan);

// Show cat information

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

while (it.hasNext()) {

System.out.println(it.next());

}

// Add a cat with the same attributes as Huahua

Cat huahua01 = new Cat(" tearful ", 12, " British short haired cat ");

set.add(huahua01);

System.out.println("");

System.out.println(" Pet cat information after adding duplicate data :");

it = set.iterator();

while (it.hasNext()) {

System.out.println(it.next());

}

System.out.println("");

// Re insert a new pet cat

Cat huahua02 = new Cat(" Huahua II ", 2, " British short haired cat ");

set.add(huahua02);

System.out.println(" Add the pet cat information after Huahua II :");

it = set.iterator();

while (it.hasNext()) {

System.out.println(it.next());

}

System.out.println("");

// Find the flower information in the collection and output

if (set.contains(huahua)) {

System.out.println(" Huahua has found !");

System.out.println(huahua);

} else {

System.out.println(" Huahua didn't find !");

}

// Use the name in the collection to find information about flowers

System.out.println("");

System.out.println(" Look up flower information by name ");

boolean flag = false;

Cat c = null;

it = set.iterator();

while (it.hasNext()) {

c = it.next();

if (c.getName().equals(" tearful ")) {

flag = true;// eureka

break;

}

}

if (flag) {

System.out.println(" Huahua has found ");

System.out.println(c);

} else {

System.out.println(" Huahua didn't find ");

}

// Delete Huahua 2's information and re output

for (Cat cat : set) {

if (" Huahua II ".equals(cat.getName())) {

set.remove(cat);

break;

}

}

System.out.println("");

System.out.println(" Delete the data after Huahua 2 generation ");

for(Cat cat:set){

System.out.println(cat);

}

// Delete all cat information in the collection

System.out.println("");

boolean flag1=set.removeAll(set);

if(set.isEmpty()){

System.out.println(" The cats are gone ...");

}else{

System.out.println(" The cat is still ...");

}

}

}

Run a screenshot

 Insert picture description here

版权声明
本文为[HUIYL1]所创,转载请带上原文链接,感谢

Scroll to Top