Javase learning notes 18: Collection (4)

The most loving girl e 2020-11-11 17:05:52
javase learning notes collection


aggregate ( Four )

HashMap and Hashtable The difference between

HashMap Of key It can be for null Do you ?value Well ? Can be empty !

package se3.themap;
import java.util.HashMap;
import java.util.Map;
public class HashMapTest03 {
public static void main(String[] args) {
Map map = new HashMap();
//HashMap The collection allows key by null
map.put(null,null);
System.out.println(map.size());//1
//key Repeated words ,value Will be covered
map.put(null,100);
System.out.println(map.size());//1
// adopt key obtain value
System.out.println(map.get(null));//100
}
}

Hashtable Of key It can be for null Do you ?value Well ? Can't be empty !

package se3.themap;
import java.util.Hashtable;
import java.util.Map;
public class HashTableTest01 {
public static void main(String[] args) {
Map map = new Hashtable();
map.put(null," APO ");
map.put(1,null);
}
}
  1. Hashtable and HashMap equally , The bottom layer is the hash table data structure
  2. Hashtable The methods are all with synchronized: Thread safe
  3. Hashtable The initialization capacity of is 11, The default load factor is 0.75
  4. Hashtable Expansion of : Original capacity *2 Again +1

Properties

​ At present, we only need to master Properties The related methods of attribute class objects can be

​ Properties It's a Map aggregate , Inherit Hashtable,Properties Of key and value All are String type

​ Properties It's called an attribute class object

​ Properties It's thread safe

package se3.themap;
import java.util.Properties;
public class PropertiesTest01 {
public static void main(String[] args) {
// Create a Properties object
Properties pro = new Properties();
// Need to master Properties Two approaches , A deposit , Take one
pro.setProperty("url","jdbc:mysql://localhost:3306/bjpowernode");
pro.setProperty("driver","com.mysql.jdbc.Driver");
pro.setProperty("username","root");
pro.setProperty("password","123");
// adopt key obtain value
String url = pro.getProperty("url");
String driver = pro.getProperty("driver");
String username = pro.getProperty("username");
String password = pro.getProperty("password");
System.out.println(url);//jdbc:mysql://localhost:3306/bjpowernode
System.out.println(driver);//com.mysql.jdbc.Driver
System.out.println(username);//root
System.out.println(password);//123
}
}

TreeSet

  1. TreeSet The bottom layer of the set is actually a TreeMap
  2. TreeMap At the bottom of the set is a binary tree
  3. Put it in TreeSet The elements in the collection , It's the same as putting TreeMap aggregate key Part of it
  4. TreeSet The elements in the collection : Disorder cannot be repeated , But it can be sorted automatically by the size of the elements , It's called a sortable set .
package se3.set;
import java.util.TreeSet;
public class TreeSetTest02 {
public static void main(String[] args) {
// establish TreeSet aggregate
TreeSet<String> ts = new TreeSet<>();
// add to String Elements
ts.add(" Qian Qi ");
ts.add(" Zhang San ");
ts.add(" Zhao Liu ");
ts.add(" Li Si ");
ts.add(" Wang Wu ");
// Traverse
for (String s : ts){
// In dictionary order , Ascending
System.out.print(s + " ");
}// Zhang San Li Si Wang Wu Zhao Liu Qian Qi
System.out.println();
TreeSet<Integer> ts2 = new TreeSet<>();
ts2.add(100);
ts2.add(200);
ts2.add(900);
ts2.add(800);
ts2.add(600);
ts2.add(10);
for (Integer elt : ts2){
// Ascending
System.out.print(elt + " ");
}//10 100 200 600 800 900
}
}

About custom type sorting

For custom types ,TreeSet Can I sort it out ? no way

  1. In the following procedure for Person In terms of type , Cannot sort . Because it is not specified Person The rules of comparison between objects
  2. It doesn't say who is big or who is small
  3. The reason for the abnormality is :Person Class does not implement java.lang.Comparable Interface .
package se3.set;
import java.util.TreeSet;
public class TreeSetTest03 {
public static void main(String[] args) {
Person p1 = new Person(32);
Person p2 = new Person(20);
Person p3 = new Person(30);
Person p4 = new Person(25);
// Additive elements
TreeSet<Person> persons = new TreeSet<>();
persons.add(p1);
persons.add(p2);
persons.add(p3);
persons.add(p4);
// Traverse
for (Person p : persons){
System.out.print(p + " ");
}
/** Running results :
* Exception in thread "main" java.lang.ClassCastException: se3.set.Person cannot be cast to java.lang.Comparable
* at java.util.TreeMap.compare(TreeMap.java:1294)
* at java.util.TreeMap.put(TreeMap.java:538)
* at java.util.TreeSet.add(TreeSet.java:255)
* at se3.set.TreeSetTest03.main(TreeSetTest03.java:18)
*/
}
}
class Person{
int age;
public Person(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" + "age=" + age + '}';
}
}

The custom rules are as follows :

package se3.set;
import java.util.TreeSet;
public class TreeSetTest04 {
public static void main(String[] args) {
Person2 p1 = new Person2(32);
Person2 p2 = new Person2(20);
Person2 p3 = new Person2(30);
Person2 p4 = new Person2(25);
// Additive elements
TreeSet<Person2> persons = new TreeSet<>();
persons.add(p1);
persons.add(p2);
persons.add(p3);
persons.add(p4);
// Traverse
for (Person2 p : persons){
System.out.println(p);
}
/**
* Running results :
* Person{age=20}
* Person{age=25}
* Person{age=30}
* Person{age=32}
*/
}
}
/*
Put it in TreeSet Elements in the collection need to implement java.lang.Comparable Interface
And realize CompareTo Method ,equals Don't write
*/
class Person2 implements Comparable<Person2>{
int age;
public Person2(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" + "age=" + age + '}';
}
// The logic of comparison needs to be written in this method , Or the method of comparison , Compare by what
//k.compareTo(t.key)
// Take the parameters k And every one of the sets k Compare , The return value may be >0 <0 =0
// Comparison rules are specified by programmers , For example, in ascending or descending order of age
@Override
public int compareTo(Person2 p) {//p1.compareTO(p2)
//this Namely p1
//p yes p2
//p1 and p2 When comparing , Namely this and p Compare
/*
int age1 = this.age;
int age2 = p.age;
if(age1 == age2){
return 0;
} else if(age1 > age2){
return 1;
} else{
return -1;
}
*/
// Abbreviation
return this.age - p.age;
}
}

About the rules of comparison

How to write ? First, in ascending order of age , If they are the same age, they will be in ascending order , Examples are as follows :

package se3.set;
import java.util.TreeSet;
// First, in ascending order of age , If they are the same age, they will be in ascending order
public class TreeSetTest05 {
public static void main(String[] args) {
TreeSet<Vip> vips = new TreeSet<>();
vips.add(new Vip("a APO ",20));
vips.add(new Vip("b APO ",20));
vips.add(new Vip(" Bobo ",18));
vips.add(new Vip(" wavelet ",17));
for (Vip vip : vips){
System.out.println(vip);
}
/**
* Output results :
* Vip{name=' wavelet ', age=17}
* Vip{name=' Bobo ', age=18}
* Vip{name='a APO ', age=20}
* Vip{name='b APO ', age=20}
*/
}
}
class Vip implements Comparable<Vip>{
String name;
int age;
public Vip(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Vip{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
/*
compareTo The return value of the method is important :
return 0 It means the same ,value Will be covered
return >0, Will continue to look for... On the right subtree 【10-9=1,1>0 The number on the left is larger , So look for... On the right subtree 】
return <0, Will continue to look for... In the left tree
*/
@Override
public int compareTo(Vip v) {
if(this.age == v.age){
// At the same age, sort by name
// The name is String type , It can be directly compared to , call compareTo Complete the comparison
return this.name.compareTo(v.name);
} else {
// Different ages
return this.age - v.age;
}
}
}

Self balanced binary tree data structure

TreeSet/TreeM It's a self balanced binary tree , Follow the principle of small left and large right ( Compare it when you store it )

Be careful : The process of storage is the process of sorting , Take out is automatically in order of size

100 200 50 60 80 120 140 130 135 180 666 40 55 After storage, it is shown in the figure below

There are three ways to traverse a binary tree

  1. The former sequence traversal : Root left and right
  2. In the sequence traversal : Left root right
  3. After the sequence traversal : Left and right

TreeSet aggregate /TreeMap The set uses : In the sequence traversal

Iterator The iterator uses the middle order traversal ( Left root right )

In the sequence traversal

Using the middle order traversal to extract :

40 50 55 60 80 100 120 140 130 135 180 200 666

Comparator mode implementation TreeSet Sort

package se3.set;
import java.util.Comparator;
import java.util.TreeSet;
/*
TreeSet The second way elements in a collection can be sorted : The way to use a comparator
*/
public class TreeSetTest06 {
public static void main(String[] args) {
// establish TreeSet When we gather , You need to use this comparator
//TreeSet<WuGui> wuGuis = new TreeSet<>();// That's not good , Without passing a comparator through the constructor
// Pass a comparator to the constructor
TreeSet<WuGui> wuGuis = new TreeSet<>(new WuGuiComparator());
wuGuis.add(new WuGui(1000));
wuGuis.add(new WuGui(800));
wuGuis.add(new WuGui(810));
for (WuGui wuGui : wuGuis){
System.out.println(wuGui);
}
/**
* Output results :
* Tortoise [age=800]
* Tortoise [age=810]
* Tortoise [age=1000]
*/
}
}
// Tortoise
class WuGui{
int age;
public WuGui(int age) {
this.age = age;
}
@Override
public String toString() {
return " Tortoise [" +
"age=" + age +
']';
}
}
// Write a comparator here alone
// Comparator implements java.util.Comparator Interface .(Comparable yes java.lang Under bag ,Comparator yes java.util Under bag )
class WuGuiComparator implements Comparator<WuGui>{
@Override
public int compare(WuGui o1, WuGui o2) {
// Specify comparison rules , Sort by age
return o1.age - o2.age;
}
}

Anonymous inner class implementation TreeSet Sort

package se3.set;
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetTest06 {
public static void main(String[] args) {
//TreeSet<WuGui> wuGuis = new TreeSet<>(new WuGuiComparator());
// Using anonymous inner classes
TreeSet<WuGui> wuGuis = new TreeSet<>(new Comparator<WuGui>() {
@Override
public int compare(WuGui o1, WuGui o2) {
return o1.age - o2.age;
}
});
wuGuis.add(new WuGui(1000));
wuGuis.add(new WuGui(800));
wuGuis.add(new WuGui(810));
for (WuGui wuGui : wuGuis){
System.out.println(wuGui);
}
/**
* Output results :
* Tortoise [age=800]
* Tortoise [age=810]
* Tortoise [age=1000]
*/
}
}
// Tortoise
class WuGui{
int age;
public WuGui(int age) {
this.age = age;
}
@Override
public String toString() {
return " Tortoise [" +
"age=" + age +
']';
}
}

Conclusion

Put it in TreeSet perhaps TreeMap aggregate key Part of the elements want to be sorted , There are two ways :

  1. Put the elements in the collection to implement java.lang.Comparable Interface
  2. In the structure TreeSet perhaps TreeMap Pass it a comparator object when assembling

Comparable and Comparator How to choose ?

When the rules of comparison don't change , Or when the rules of comparison are only 1 When it's time , It is recommended to use Comparable Interface .

If there are more than one comparison rule , And it requires frequent switching between multiple comparison rules , It is recommended to use Comparator Interface .

Collections Tool class

package se3.collection;
import java.util.*;
/*
java.util.Collection Collection interface
java.util.Collections Collection tool class , To facilitate the operation of sets .
*/
public class CollectionsTest01 {
public static void main(String[] args) {
//ArrayList Collection is not thread safe
List<String> list = new ArrayList<>();
// Become thread safe
Collections.synchronizedList(list);
list.add("abf");
list.add("abx");
list.add("abc");
list.add("abe");
// Sort
Collections.sort(list);
for (String s : list){
System.out.print(s + " ");
}//abc abe abf abx
System.out.println();
List<WuGui2> wuGui2s = new ArrayList<>();
wuGui2s.add(new WuGui2(1000));
wuGui2s.add(new WuGui2(8000));
// Be careful : Yes List Sort the elements in a collection , Need assurance List The elements in the collection implement Comparable Interface
Collections.sort(wuGui2s);
for (WuGui2 wuGui2 : wuGui2s){
System.out.println(wuGui2);
}
/*
Tortoise [age=1000]
Tortoise [age=8000]
*/
//Set Collection sorting
Set<String> set = new HashSet<>();
set.add("king");
set.add("kingsoft");
set.add("king2");
set.add("king1");
// take Set Set to List aggregate
List<String> mylist = new ArrayList<>(set);
Collections.sort(mylist);
for (String s : mylist){
System.out.print(s + " ");
}//king king1 king2 kingsoft
}
}
class WuGui2 implements Comparable<WuGui2>{
int age;
public WuGui2(int age) {
this.age = age;
}
@Override
public int compareTo(WuGui2 o) {
return this.age - o.age;
}
@Override
public String toString() {
return " Tortoise [" +
"age=" + age +
']';
}
}
版权声明
本文为[The most loving girl e]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云