Summary of Day 17 - -------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1: Login Registration Case (Understanding)
2:Set Sets (Understanding)
(1) Characteristics of Set Sets
Disorder, uniqueness
(2)HashSet Collection (Mastery)
A: The underlying data structure is a hash table (an array of linked elements)
B: The underlying hash surface depends on two methods: hashCode() and equals().
Execution order:
First, compare whether hash values are the same
Same: Continue to execute the equals() method
Return true: The element is repeated, not added
Return false: Add elements directly to the collection
The difference: add elements directly to the collection
C: How to guarantee the uniqueness of elements?
Guaranteed by hashCode() and equals()
D: When developing, the code is very simple and can be generated automatically.
E:HashSet stores strings and traverses them
F:HashSet stores custom objects and traverses them (objects whose member variables have the same value are the same elements)
(3)TreeSet collection
A: The underlying data structure is a red-black tree (a self-balanced binary tree)
B: Guarantee the sorting of elements
a: Natural ordering (elements are comparative)
Implementing Comparable interfaces for classes to which elements belong
b: Comparator sorting (sets have comparability)
Let Collection Constructor Receive Comparator Implementation Class Objects
C: Just look at the code we talked about.
(4) Cases:
A: Acquire random numbers without duplication
B: Keyboard entry students output from high to low according to the total score
3:Collection Set Summary (Mastery)
Collection
| List is orderly and repeatable
|–ArrayList
The underlying data structure is an array, query fast, add or delete slowly.
Threads are insecure and efficient
|–Vector
The underlying data structure is an array, query fast, add or delete slowly.
Thread Safety and Low Efficiency
|–LinkedList
The underlying data structure is linked list, which is slow to query and fast to add or delete.
Threads are insecure and efficient
| Set, disorder, uniqueness
|–HashSet
The underlying data structure is a hash table.
How to ensure the uniqueness of elements?
Depends on two methods: hashCode() and equals()
These two methods can be automatically generated in development.
|–LinkedHashSet
The underlying data structure is linked list and hash table
Ensuring Element Order by Chain List
Guarantee element uniqueness by hash table
|–TreeSet
The underlying data structure is a red-black tree.
How to ensure that elements are sorted?
Natural Sorting
Comparator sort
How to ensure the uniqueness of elements?
Decide whether the return value of the comparison is 0 or not
4: Who exactly do we use for Collection collections?
Is it the only one?
Yes: Set
Ordering?
Yes: TreeSet
No: HashSet
If you know Set, but you don't know which Set it is, use HashSet.
No: List Is it safe? Yes: Vector No: ArrayList or LinkedList Multiple queries: ArrayList Add, delete and add: LinkedList If you know it's a List, but you don't know which List it is, use ArrayList. If you know it's a Collection collection, but you don't know who to use, use ArrayList. If you know how to use collections, use ArrayList.
5: Common data structures in collections (mastery)
ArrayXxx: The underlying data structure is an array, querying fast, adding or deleting slow
LinkedXxx: The underlying data structure is linked list, which is slow to query and fast to add or delete.
HashXxx: The underlying data structure is a hash table. Depends on two methods: hashCode() and equals()
TreeXxx: The underlying data structure is a binary tree. Two Sorting Ways: Natural Sorting and Comparator Sorting
----------------------------------------------------------- Knowledge Point 1 - -------------------------------------------------------------------------------------------------------------
Requirements: User login registration case.
By following these operations, we can symbolize the object-oriented idea more.
A: What are the categories?
B: What's in each class?
C: What is the relationship between classes?
Analysis:
A: What are the categories?
User class
Test class
B: What's in each class?
User class:
Membership variables: username, password
Construction method: parametric structure
Membership methods: getXxx()/setXxx()
Log in, register
If the content of user class is correct, it will be more troublesome to maintain in the future. In order to classify users more clearly, we divide users into two categories. User Basic Description Class Membership variables: username, password Construction method: parametric structure Membership methods: getXxx()/setXxx() User Operations Class Log in, register Test class: main method. C: What is the relationship between classes? Create the object of user operation class and user basic description class in the test class and use its function.
To subcontract:
A: Functional Division
B: Modular Partitioning
C: First by module, then by function.
Today we choose to divide it by function:
User Basic Description Package cn.itcast.pojo
User Operating Interface cn.itcast.dao
User Operations Class Package cn.itcast.dao.impl
Today is the collective implementation, IO implementation in a few days, GUI implementation in a few days, we are the database implementation in the employment class.
User test class cn.itcast.test
package cn.itcast.dao;
import cn.itcast.pojo.User;
/**
-
This is an interface for users to operate on.
-
This is an interface for users to operate on.
-
@ author Chen Xiaokang
-
/
public interface UserDao {
/*- This is the user login function
*@param username
-
User name
*@param password
-
Password
- @ Whether the return login was successful or not
- */
public abstract boolean isLogin (String username,String password);
/**
- This is the user registration function.
- @ Information to be registered by param user
- */
public abstract void regist(User user);
}
package cn.itcast.dao.Ipml;
import java.util.ArrayList;
import cn.itcast.dao.UserDao;
import cn.itcast.pojo.User;
/**
- This is the concrete implementation class for user actions (Collection Edition)
- @ author Chen Xiaokang
- @version V1.0
- */
public class UserDaoImpl implements UserDao {
// Store user information in a collection
// To allow multiple methods to use the same set, a set is defined as a member variable.
// In order not to be seen by outsiders, it is defined as private.
private static ArrayList array = new ArrayList();
@Override public boolean isLogin(String username, String password) { // Traverse the collection to determine whether the username and password match in the collection boolean flag = false; for(User u:array){ if(u.getUsername().equals(username)&& u.getPassword().equals(password)){ flag = true; break; } } return flag; } @Override public void regist(User user) { array.add(user); }
}
package cn.itcast.game;
import java.util.Random;
import java.util.Scanner;
/**
-
This is a number guessing game class.
-
@ author Chen Xiaokang
-
@version V1.0
-
*/
public class GuessNumberGame {
public static void playGame(){
// Creating Random Number Objects
Random rd = new Random();
int result = rd.nextInt(100)+1;
System.out.println("Start the game!" );// Define a statistical variable int count =0; while(true){ // Keyboard input data Scanner sc = new Scanner(System.in); System.out.print("Please enter the number you guessed.(1-100):"); int GuessNumber = sc.nextInt(); count++; if(GuessNumber>result){ System.out.println("Your guess is big."); }else if(GuessNumber<result){ System.out.println("Your guess is small."); }else{ System.out.println("Congratulations on your passing"+count+"That's the right answer. The answer is:"+result); break; } }
}
}
package cn.itcast.pojo;
/**
- @ author Chen Xiaokang
- @version V1.0
*/
public class User {
// Define user names
private String username;
// Define passwords
private String password;
// Parametric-free construction method public User() { super(); } // Acquisition method public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package cn.itcast_01;
import java.util.HashSet;
import java.util.Set;
/*
-
Collection
-
List
-
Ordered (in the same order of storage and removal), repeatable
-
Set
-
Unordered (inconsistent order of storage and extraction), unique and unable to contain duplicate elements
-
Although the elements of a Set collection are out of order, as a collection type, it must have its own storage order.
-
And your order is exactly the same as its storage order, which does not mean orderly, you can store more data, you can see the effect.
-
HashSet: It does not guarantee the sequence of iterations of a set; in particular, it does not guarantee that the sequence will remain constant.
-
*/
public class SetDemo {
public static void main(String[] args) {
// Creating Collection Objects
Set set = new HashSet();// Create and add elements set.add("hello"); set.add("world"); set.add("java"); set.add("hello"); set.add("world"); set.add("java"); // Enhanced for for(String s:set){ System.out.println(s); }
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package cn.itcast_02;
import java.util.HashSet;
/*
-
Requirements: HashSet stores strings and traverses them
-
From the original code of the add method, we know that this method relies on two methods: hasCode() and equals().
-
Steps:
-
First compare hash values
-
If the same, compare the address value or equalds()
-
If it's different, add it directly to the collection
-
*/
public class HashSetDemo {
public static void main(String[] args) {
// Create collections
HashSet hs = new HashSet();// Adding elements hs.add("hello"); hs.add("world"); hs.add("java"); hs.add("world"); // Enhanced for traversal for(String s :hs){ System.out.println(s); }
}
}
------------------------------------------------------------- Knowledge Point 4 - ---------------------------------------------------------------------------------------------
package cn.itcast_02;
import java.util.HashSet;
/*
-
Requirements: Store custom objects and ensure the uniqueness of elements
-
Requirement: If the member variable values of both objects are the same, they are the same element.
-
At present, it does not meet the requirements, because the student class does not rewrite the two methods because it relies on HashCode() and equals() methods.
-
*/
public class HashSetDemo2 {
public static void main(String[] args) {
// Create collections
HashSet hs = new HashSet();// Creating Student Objects Student s1 = new Student("Tang Seng",12); Student s2 = new Student("Sun WuKong",600); Student s3 = new Student("Zhu Bajie",543); Student s4 = new Student("Sha Seng",323); Student s5 = new Student("White Dragon Horse",342); Student s6 = new Student("Tang Seng",12); Student s7 = new Student("Sun WuKong",600); Student s8 = new Student("Sun WuKong",601); // Adding elements hs.add(s1); hs.add(s2); hs.add(s3); hs.add(s4); hs.add(s5); hs.add(s6); hs.add(s7); hs.add(s8); // Traversing output arrays for(Student s:hs){ System.out.println(s.getName()+"---"+s.getAge()); }
}
}
------------------------------------------------------------- Knowledge Point 5 - -----------------------------------------------------------------------------------------------------------
package cn.itcast_03;
public class Dog {
// Define name
private String name;
// Define age
private int age;
// Define color
private String color;
public Dog() { super(); // TODO Auto-generated constructor stub } public Dog(String name, int age, String color) { super(); this.name = name; this.age = age; this.color = color; } 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; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((color == null) ? 0 : color.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Dog other = (Dog) obj; if (age != other.age) return false; if (color == null) { if (other.color != null) return false; } else if (!color.equals(other.color)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package cn.itcast_03;
/*
-
The HashSet collection stores custom objects and traverses them.
If the member variables of an object have the same value, they are the same object.Be careful:
Using the HashSet collection, the underlying structure of the collection is the hash structure
The underlying dependencies of hash table structure are hashCode() and equals() methods.
These two methods need to be overridden if the member variable values are treated as the same object. -
*/
import java.util.HashSet;
public class DogDemo {
public static void main(String[] args) {
// Create a HashSet collection
HashSet hs = new HashSet();
// Creating Dog Objects Dog d1 = new Dog("Prosperous wealth",8,"red"); Dog d2 = new Dog("Wheezing dog",10,"yellow"); Dog d3 = new Dog("Poodle",8,"yellow"); Dog d4 = new Dog("Two ha",11,"black"); Dog d5 = new Dog("Two ha",12,"black"); Dog d6 = new Dog("Poodle",8,"yellow"); // Collection Add Elements hs.add(d1); hs.add(d2); hs.add(d3); hs.add(d4); hs.add(d5); hs.add(d6); // Traverse the set to find elements with the same member variables for(Dog d:hs){ System.out.println(d.getName()+"---"+d.getAge()+"---"+d.getColor()); } }
}
----------------------------------------------------------- Knowledge Point 7 - -----------------------------------------------------------------------------------------------------------
package cn.itcast_04;
import java.util.LinkedHashSet;
/*
-
LinkedHashSet: The underlying data structure consists of hash lists and linked lists
-
Hash table guarantees the uniqueness of elements
-
The list ensures that the elements are in order. (Storage and retrieval alignment)
-
*/
public class LinkedHashSetDemo {
public static void main(String[] args) {
// Create collections
LinkedHashSet lhs = new LinkedHashSet();// Adding elements lhs.add("hello"); lhs.add("world"); lhs.add("java"); // Cyclic traversal for(String s:lhs){ System.out.println(s); }
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package cn.itcast_05;
import java.util.TreeSet;
/*
-
TreeSet: Ability to sort elements according to certain rules
-
There are two ways to sort:
-
1. Natural Sorting
-
2. Comparator sorting
-
TreeSet features:
-
sort
-
Only
-
*/
public class TreeSetDemo {
public static void main(String[] args) {
// Create collections
TreeSet ts = new TreeSet();// Adding elements ts.add(12); ts.add(13); ts.add(9); ts.add(10); ts.add(12); ts.add(8); ts.add(18); ts.add(9); // Enhanced for loop traversal for(Integer i:ts){ System.out.println(i); }
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package cn.itcast_05;
import java.util.TreeSet;
/*
-
TreeSet stores custom objects and guarantees sorting and uniqueness.
-
*/
public class TreeSetDemo2 {
public static void main(String[] args) {
// Creating Collection Objects
TreeSet ts = new TreeSet();// Creating Student Objects Student s1 = new Student("lingqingxia",12); Student s2 = new Student("sunwukong",600); Student s3 = new Student("zhubajie",543); Student s4 = new Student("shaseng",323); Student s5 = new Student("bailongma",342); Student s6 = new Student("tangsheng",12); Student s7 = new Student("shasheng",323); ts.add(s1); ts.add(s2); ts.add(s3); ts.add(s4); ts.add(s5); ts.add(s6); ts.add(s7); // Cyclic traversal for(Student s : ts){ System.out.println(s.getName()+"---"+s.getAge()); }
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
TreeSet's add() method source code parsing:
interface Collection{}
class Set extends Collection{}
interface NavigableMap{}
class TreeMap implements NavigableMap{
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
compare(key, key); // type (and possibly null) check
root = new Entry<>(key, value, null); size = 1; modCount++; return null; } int cmp; Entry<K,V> parent; // split comparator and comparable paths Comparator<? super K> cpr = comparator; if (cpr != null) { do { parent = t; cmp = cpr.compare(key, t.key); if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null); } else { if (key == null) throw new NullPointerException(); @SuppressWarnings("unchecked") Comparable<? super K> k = (Comparable<? super K>) key; do { parent = t; cmp = k.compareTo(t.key); if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null); } Entry<K,V> e = new Entry<>(key, value, parent); if (cmp < 0) parent.left = e; else parent.right = e; fixAfterInsertion(e); size++; modCount++; return null; }
}
class TreeSet implements Set{
private transient NavigableMap<E,Object> m;
// Parametric structure public TreeSet() { this(new TreeMap<E,Object>()); } public boolean add(E e) { return m.put(e, PRESENT)==null; }
}
The real comparison depends on the compareTo() method of the element, which is defined in Comparable.
Therefore, if you want to rewrite this method, you must implement the Comparable interface. This interface represents natural sorting.
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package cn.itcast_06;
import java.util.TreeSet;
/*
-
Requirements: Sort by name length
-
*/
public class TreeSetDemo {
public static void main(String[] args) {
// Creating Collection Objects
TreeSet ts = new TreeSet();// Creating Student Objects Student s1 = new Student("lingqingxia",12); Student s2 = new Student("sunwukong",600); Student s3 = new Student("zhubajie",543); Student s4 = new Student("shasheng",323); Student s5 = new Student("bailongma",342); Student s6 = new Student("tangsheng",12); Student s7 = new Student("shasheng",323); Student s8 = new Student("shasheng",324); ts.add(s1); ts.add(s2); ts.add(s3); ts.add(s4); ts.add(s5); ts.add(s6); ts.add(s7); ts.add(s8); // Cyclic traversal for(Student s : ts){ System.out.println(s.getName()+"---"+s.getAge()); }
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package cn.itcast_07;
import java.util.Comparator;
import java.util.TreeSet;
/*
-
Requirements: Sort by name length
-
The Principle of TreeSet Set Set Ensuring Element Sorting and Uniqueness
-
Uniqueness: It depends on whether the return of the comparison is zero.
-
Sort:
-
1. Natural Sorting (Elements are comparative)
-
Let the class to which the element belongs implement the natural sorting interface Comparable
-
2. Comparator Sorting (Sets with Comparators)
-
Let the constructor of a collection receive a subclass object Comparator of a comparator interface
-
*/
public class TreeSetDemo {
public static void main(String[] args) {
// Creating Collection Objects
// TreeSet ts = new TreeSet(); // Natural Sorting
// public TreeSet(Comparator comparator) comparator sort
// TreeSet ts = new TreeSet(new MyComparator());// If the parameter of a method is an interface, then the implementation class object of the interface that is really needed // Anonymous inner classes can do this. TreeSet <Student> ts = new TreeSet<Student>(new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { int num =s1.getName().length()-s2.getName().length(); int num2 = (num==0)?(s1.getName().compareTo(s2.getName())):num; int num3 =(num2==0)?(s1.getAge()-s2.getAge()):num2; return num3; } }); // Creating Student Objects Student s1 = new Student("lingqingxia",12); Student s2 = new Student("sunwukong",600); Student s3 = new Student("zhubajie",543); Student s4 = new Student("shasheng",323); Student s5 = new Student("bailongma",342); Student s6 = new Student("tangsheng",12); Student s7 = new Student("shasheng",323); Student s8 = new Student("shasheng",324); ts.add(s1); ts.add(s2); ts.add(s3); ts.add(s4); ts.add(s5); ts.add(s6); ts.add(s7); ts.add(s8); // Cyclic traversal for(Student s : ts){ System.out.println(s.getName()+"---"+s.getAge()); }
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package cn.itcast_07;
import java.util.Comparator;
public class MyComparator implements Comparator {
@Override public int compare(Student s1, Student s2) { int num =s1.getName().length()-s2.getName().length(); int num2 = (num==0)?(s1.getName().compareTo(s2.getName())):num; int num3 =(num2==0)?(s1.getAge()-s2.getAge()):num2; return num3; }
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package cn.itcast_07;
import java.util.Comparator;
/*
*
*
-
*/
public class Student implements Comparator {
// Membership variables
private String name;
private int age;// Construction method
public Student() {
super();
// TODO Auto-generated constructor stub
}public Student(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;
}@Override
public int compare(Student s1, Student s2) {
int num =s1.getName().length()-s2.getName().length();
int num2 = (num0)?(s1.getName().compareTo(s2.getName())):num;
int num3 =(num20)?(s1.getAge()-s2.getAge()):num2;return num3;
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package cn.itcast_08;
import java.util.HashSet;
import java.util.Random;
/*
-
Requirement: Write a program to obtain 10 to 20 random numbers, requiring that random numbers should not be repeated.
-
Analysis:
-
1. Create random number objects
-
2. Create a HashSet collection
-
3. Determine whether the length of the set is 10
-
If not, continue adding iteratively
-
If so, stop adding
-
*/
public class HashSetDemo {
public static void main(String[] args) {
// Creating Random Number Objects
Random rd = new Random();// Create a HashSet collection HashSet<Integer> hs = new HashSet<Integer>(); while(hs.size()!=10){ //if(!hs.contains(rd.nextInt(19)+1)){ hs.add(rd.nextInt(20)+1); //} }
// traversal output set
for(Integer i:hs){
System.out.println(i);
}}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package cn.itcast_08;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Scanner;
import java.util.TreeSet;
/*
-
Keyboard input 5 student information (name, Chinese score, math score, English score), according to the total score from high to low output to the console
-
1. Creating Student Classes
-
2. Create a TreeSet collection
-
3. Keyboard Entry Student Information
-
4. Adding students to the collection
-
4. Sort out the elements in the TreeSet set according to the total score
-
a. Natural Sorting Method
-
b. Comparator comparison
-
*/
public class TreeSetDemo {
public static void main(String[] args) {
// Create collections
TreeSet ts = new TreeSet();// Creating Student Objects // Create keyboard entry objects //Student [] s = {s1,s2,s3,s4,s5}; for(int x=0;x<3;x++){ Scanner sc = new Scanner(System.in); Student s = new Student(); // Name of enrolled students System.out.println("Please enter"+(x+1)+"Name of each student:"); String name = sc.nextLine(); s.setName(name); // Input Chinese Achievements System.out.println("Please enter"+(x+1) + "Language Achievements of Individual Students:"); float chinese = sc.nextFloat(); s.setChinese(chinese); // Enter Mathematical Achievements System.out.println("Please enter"+(x+1) + "Mathematics Achievements of Individual Students"); float math = sc.nextFloat(); s.setMath(math); // Enter English Achievements System.out.println("Please enter"+(x+1) + "English Achievements of Individual Students"); float english = sc.nextFloat(); s.setEnglish(english); // Add students to collections ts.add(s); } System.out.println("Finish adding!"); // Ergodic output int count = 0; System.out.println("--------------------School report--------------------"); System.out.println("Full name\t Chinese\t Mathematics\t English?\t Total score\t ranking"); for(Student ss:ts){ BigDecimal bd1 = new BigDecimal(ss.getChinese(),new MathContext(4)); BigDecimal bd2 = new BigDecimal(ss.getMath(),new MathContext(4)); BigDecimal bd3 = new BigDecimal(ss.getEnglish(),new MathContext(4)); BigDecimal sum = Student.Score_Sum(ss.getChinese(),ss.getMath(),ss.getEnglish()); count++; // System.out.println(ss.getName()+"\t"+ss.getChinese()+ // "\t"+ss.getMath()+"\t"+ss.getEnglish()+"\t"+(ss.getChinese()+ // ss.getMath()+ss.getEnglish())+"\t"+count); System.out.println(ss.getName()+"\t"+bd1+"\t"+bd2+"\t"+bd3+"\t"+sum+"\t"+count); } System.out.println("---------------------------------------------");
}
}