2019-05-27 Java Learning Diary day17
Posted by ruuyx on Mon, 27 May 2019 22:55:12 +0200
Hashset set
Store strings and traverse them
import java.util.HashSet;
public class dmo1_hashset {
//set Collection, no index, no repetition, no order(Access inconsistency)
public static void main(String[] args) {
HashSet<String> hSet=new HashSet<>(); //Establish hashset object
boolean b1=hSet.add("a");
boolean b2=hSet.add("a"); //When direction set When duplicate elements are stored in a collection, they are returned as false
hSet.add("b");
hSet.add("c");
hSet.add("d");
System.out.println(hSet); //hashset There is rewriting in the system of inheritance toString Method
//System.out.println(b1);
//System.out.println(b2);
for (String string : hSet) { //Enhancements can be used as long as they can be iterated with iterators for Cyclic traversal
System.out.println(string);
}
}
}
case
Storing custom objects guarantees element uniqueness
Hashset Principle
We need to remove duplicate elements when we use set sets. If we compare equals () one by one, the efficiency is lower. Hash algorithm improves the efficiency of duplication and reduces the number of times using equals () method.
When Hashset calls the add () method to store an object, it first calls the HashSet () method of the object to get a hash value, and then finds out whether there is an object with the same hash value in the collection:
If no object with the same hash value is stored directly in the collection
If there is an object with the same hash value, the object with the same hash value is compared with equals () one by one, and the result of comparison is false and true does not exist.
Store custom cumulative objects in Hashset to repeat
hashCode () and equals () methods must be overridden in the class
hashCode (): Objects with the same attributes have the same return value, while objects with different attributes have different return values as far as possible (to improve efficiency)
equals (): the same attribute returns true, different attribute returns false, when returned false
import java.util.HashSet;
import tan.jung.bean.Person;
public class demo2_hashset {
public static void main(String[] args) {
HashSet<Person> hs =new HashSet<>();
hs.add(new Person("Zhang San",23));
hs.add(new Person("Zhang San",23));
hs.add(new Person("Zhang San",23));
hs.add(new Person("Li Si",24));
hs.add(new Person("Li Si",24));
System.out.println(hs); //Need to rewrite equals and HashCode Method
}
}
//Second bags
public class Person {
private String name;
private int 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;
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
/*@Override
public boolean equals(Object obj) {
System.out.println("Implemented "";
Person p=(Person)obj;
return this.name.equals(p.name) && this.age == p.age;
}
@Override
public int hashCode() {
final int num=38;
return name.hashCode() * num +age;
}*/
@Override
public int hashCode() {
final int prime = 31; //31 It's a prime number. A prime number is a number that can be divided by 1 and itself. It's not too big or too small. It's better to calculate. The fifth power of 2.-1,2 Move five bits to the left
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) //The invoked object and the incoming object are the same object
return true; //Direct return rute
if (obj == null) //The incoming object is null
return false; //Return false
if (getClass() != obj.getClass()) //Determine whether the bytecode corresponding to two objects is not the same bytecode?
return false; //If not returned directly false
Person other = (Person) obj; //Downward transformation
if (age != other.age) //The year of the calling object is not equal to the age of the incoming object
return false; //Return false
if (name == null) { //The name of the calling object is not null
if (other.name != null) //The name of the incoming object is not null
return false; //Return false
} else if (!name.equals(other.name)) //The name of the calling object is not equal to the name of the incoming object
return false; //Return flase
return true; //Return true
}
}
LinkedHashset
Characteristic:
It can be guaranteed that you can take whatever you deposit.
The bottom layer is implemented jointly and severally, and is the only set set set set set that guarantees how to store and how to get set objects.
Because of Hashset's subclasses, it is also guaranteed that elements are unique, just like Hashset's principle.
random number
public class test1 {
public static void main(String[] args) {
//Establish Random Class Creates Random Number Objects
Random r1=new Random();
//It can't be repeated. It needs to be used. Hashset Method
HashSet<Integer> hs1=new HashSet<>();
//hashset Of size If it rains 10, it can be stored continuously. If it is more than or equal to 10, it will stop storing.
while (hs1.size()<10) {
//adopt random Class nextInt(n)Method Obtain random numbers between 1 and 20 and save them now. hashset Collection
hs1.add(r1.nextInt(21));
}
//ergodic Hashset
for (Integer integer : hs1) {
System.out.println(integer);
}
}
Exercises
Keyboard input, remove duplication
import java.util.HashSet;
import java.util.Scanner;
import javax.sound.sampled.Line;
public class test2 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Please input");
//Establish Hashset Exclusive, Store Characters, Remove Duplication
HashSet<Character> hs1 =new HashSet<>();
//Converting strings into character arrays to get each character stored in Hashset In collections, duplicates are automatically removed
String line=sc.nextLine();
char[] arr=line.toCharArray();
for (char c : arr) { //Traversing character arrays
hs1.add(c);
}
//ergodic Hashset,Print each character
for(Character ch:hs1){
System.out.println(ch);
}
}
}
Exercises
Removing duplication in a set
import java.util.ArrayList;
import java.util.LinkedHashSet;
public class test3 {
public static void main(String[] args) {
ArrayList<String> list=new ArrayList<>();
list.add("a");
list.add("a");
list.add("a");
list.add("a");
list.add("b");
list.add("b");
list.add("c");
getSingle(list); //Calling method
System.out.println(list);
}
public static void getSingle(ArrayList<String> list) {
LinkedHashSet<String> lsh=new LinkedHashSet<>();
lsh.addAll(list); //Add to list element
list.clear(); //Eliminate list element
list.addAll(lsh); //take LinkedHashset Element addition in a collection list Collection
}
}
Exercises
TreeSet
Treeset stores Integer-type elements and traverses them
import java.util.TreeSet;
public class demo4_TreeSet {
//TreeSet Collections are used to sort object elements, and colleagues can guarantee the uniqueness of elements.
public static void main(String[] args) {
TreeSet<Integer> ts1=new TreeSet<>();
ts1.add(1);
ts1.add(1);
ts1.add(2);
ts1.add(2);
ts1.add(3);
ts1.add(3);
ts1.add(3);
ts1.add(4);
ts1.add(4);
System.out.println(ts1);
}
}
case
TreeSet stores custom objects
Binary number: two forks
Small ones are stored on the left (negative), and typed ones are stored on the right (integer). Equal ones do not exist (0).
The compareTo method, how elements are stored in the TreeSet collection, depends on the return value of the compareTo method
Returns 0, with only one element in the collection
Returning negative sets will reverse the stored elements
How to save and fetch integers when they are returned
import java.util.Iterator;
import java.util.TreeSet;
import tan.jung.bean.Person;
/*When the compareTo method returns 0, there is only one element in the collection.
*When the compareTo method returns an integer, the collection is saved as it is taken.
*When the compareTo method returns a negative number, the collection is stored in reverse order.
* */
public class demo5_TreeSet {
public static void main (String args[]){
TreeSet<Person> ts1=new TreeSet<>();
ts1.add(new Person("xx",20));
ts1.add(new Person("hh",20));
ts1.add(new Person("nn",20));
ts1.add(new Person("mm",20));
Iterator<Person> it1=ts1.iterator();
while (it1.hasNext()) {
Person p1=it1.next();
System.out.println(p1.getName()+" "+p1.getAge());
}
//System.out.println(ts1);
}
}
//Second bags
public class Person implements Comparable<Person>{
private String name;
private int 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;
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
/*@Override
public boolean equals(Object obj) {
System.out.println("Implemented "";
Person p=(Person)obj;
return this.name.equals(p.name) && this.age == p.age;
}
@Override
public int hashCode() {
final int num=38;
return name.hashCode() * num +age;
}*/
@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;
}
@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;
}
@Override
public int compareTo(Person o) {
return -1;
}
}
case
Sort by name
Sort by age
import java.util.Iterator;
import java.util.TreeSet;
import tan.jung.bean.Person;
/*When the compareTo method returns 0, there is only one element in the collection.
*When the compareTo method returns an integer, the collection is saved as it is taken.
*When the compareTo method returns a negative number, the collection is stored in reverse order.
* */
public class demo5_TreeSet {
public static void main (String args[]){
//demo1();
TreeSet<Person> ts1=new TreeSet<>();
ts1.add(new Person("Zhang San",20));
ts1.add(new Person("Li Si",12));
ts1.add(new Person("Wang Wu",25));
ts1.add(new Person("Zhao Liu",11));
ts1.add(new Person("77",11));
System.out.println('Zhang'+0);
System.out.println('plum'+0);
System.out.println('king'+0);
System.out.println('Zhao'+0);
System.out.println('Seven'+0);
Iterator<Person> it1=ts1.iterator();
while (it1.hasNext()) {
Person p1=it1.next();
System.out.println(p1.getName()+" "+p1.getAge());
}
}
public static void demo1() {
TreeSet<Person> ts1=new TreeSet<>();
ts1.add(new Person("xx",20));
ts1.add(new Person("hh",12));
ts1.add(new Person("nn",25));
ts1.add(new Person("mm",11));
ts1.add(new Person("ss",11));
Iterator<Person> it1=ts1.iterator();
while (it1.hasNext()) {
Person p1=it1.next();
System.out.println(p1.getName()+" "+p1.getAge());
}
}
}
//Second bags
import java.awt.RenderingHints;
public class Person implements Comparable<Person>{
private String name;
private int 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;
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
/*@Override
public boolean equals(Object obj) {
System.out.println("Implemented "";
Person p=(Person)obj;
return this.name.equals(p.name) && this.age == p.age;
}
@Override
public int hashCode() {
final int num=38;
return name.hashCode() * num +age;
}*/
@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;
}
@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;
}
/*@Override
public int compareTo(Person o) {
int num =this.age-o.age; //Age is the main condition
return num==0 ? this.name.compareTo(o.name) : num;
}*/
@Override
public int compareTo(Person o) {
int num=this.name.compareTo(o.name);
int num2=this.age-o.age;//Name is the main condition
return num==0 ? num2 :num;
}
}
case
Sort by name length
public int compareTo(Person o) {
int length =this.name.length() - o.name.length(); //The main condition is comparative length.
int num =length == 0? this.name.compareTo(o.name) :length;//Content of comparison is a secondary condition
//If length If it's equal to zero, it's a comparison. this.name.compareTo(o.name) ,compare Comparative content
//If it's not equal to zero, compare it. length
return num ==0 ? this.age-o.age :num; //Age comparison is a secondary condition
}
Method
Interfaces cannot directly need to be given subclass objects by new
public class demo5_TreeSet {
public static void main (String args[]){
//demo1();
//demo2();
//demo3();
TreeSet<String> ts1=new TreeSet<>(new CompareByLen());
//compare c=new CompareByLen();
ts1.add("abccd");
ts1.add("z");
ts1.add("bb");
ts1.add("sss");
System.out.println(ts1);
}
}
class CompareByLen implements Comparator<String>{
@Override
public int compare(String s1, String s2) { //Compare by string length
int num =s1.length() -s2.length(); //Length is the main condition
return num == 0 ?s1.compareTo(s2) : num ; //Content as a secondary condition
}
}
case
TreeSet Principle
Characteristic:
TreeSet is used for sorting, and you can specify a sequence in which objects are placed.
How to use it:
1. Comparable
The add () method of the TreeSet class elevates the stored object to a Comparable type
Comparisons between compareTo () methods of invoking objects and objects in Collections
Store the results returned by compareTo () method
2. Comparator sequence
Create a Comparatpr when creating TreeSet
If a subclass object of Comparator is passed in, the TreeSet will be sorted in the order in the comparator
Comparator interface comparison () method sorting is automatically invoked within add () violation
The object invoked is the first parameter of the compare () method, and the object in the collection is the second parameter of the compare method.
3. The difference between the two ways:
The TreeSet constructor passes nothing, defaulting to the order of Comparable s in the class (ClassCasException is reported without error)
TreeSet is preferred to Comparator if it is passed in
Topics:
PHP
Java
Attribute