Javase learning notes 16: Collection (2)

The most loving girl e 2020-11-08 16:58:52
javase learning notes collection


aggregate ( Two )

About set elements remove

During iteration , Elements cannot be deleted directly through collection , To delete elements through iterators

package se3.collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionTest06 {
public static void main(String[] args) {
Collection c = new ArrayList();
c.add(1);
c.add(2);
c.add(3);
Iterator it = c.iterator();
while (it.hasNext()){
// When writing code next() Method return value type must be Object
Object obj = it.next();
//c2.remove();// Delete elements directly through the collection , There is no notification iterator , Will report a mistake
// Use iterators to delete
it.remove();// It must be the current element that the iterator points to
System.out.println(obj);
}
System.out.println(c.size());//0
}
}

List Interface specific methods

test List Common methods in interface
  1. List Collection storage element characteristics : Orderly and repeatable

    Orderly :List The elements in the set have subscripts , from 0 Start , With 1 Increasing

    repeatable : Store a 1, It can also be stored in 1

  2. List Since it is Collection The child interface of the interface , So sure List The interface has its own “ features ” Methods :

    Only... Are listed below List Common methods of interface

    ​ void add(int index,Object element)

    ​ Object get(int index)

    ​ int indexOf(Object o)

    ​ int lastIndexOf(Object o)

    ​ Object remove(int index)

    ​ Object set(int index,Object element)

package se3.list;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class ListTest01 {
public static void main(String[] args) {
// establish List A collection of types
List myList = new ArrayList();
//List myList = new LinkedList();
// Additive elements
myList.add("A");// By default, all elements are added to the end of the collection
myList.add("B");
myList.add("C");
myList.add("C");
myList.add("D");
// Add the specified element in the specified position ( The first parameter is the subscript )
// Not much , Yes ArrayList The efficiency is relatively low
myList.add(1,"KING");
// iteration
Iterator it = myList.iterator();
while (it.hasNext()){
Object obj = it.next();
System.out.print(obj + " ");
}
// Running results :A KING B C D
System.out.println();
// Get elements according to subscripts
Object obj1 = myList.get(0);
System.out.println(obj1);//A
// Because there are subscripts , therefore list The collection has its own special traversal way
// Traverse by subscript (List A unique way to assemble ,Set No, )
for (int i = 0; i < myList.size(); i++) {
Object object = myList.get(i);
System.out.print(object + " ");
}// Running results :A KING B C D
System.out.println();
// Gets the index at the first occurrence of the specified object
System.out.println(myList.indexOf("KING"));//1
// Gets the index at the last occurrence of the specified object
System.out.println(myList.lastIndexOf("C"));//4
// Delete the element with the specified subscript
// Delete the subscript as 0 The elements of
myList.remove(0);
System.out.println(myList.size());//5
// Modify the element at the specified location
myList.set(2,"Soft");
// Traverse
for (int i = 0; i < myList.size(); i++) {
Object object = myList.get(i);
System.out.print(object + " ");
}
// Running results :KING B Soft C D
}
}

ArrayList aggregate

ArrayList Set initialization capacity and expansion
1. The default initialization capacity is 10( The bottom layer first creates a length of 0 Array of , When you add the first element , The initialization capacity is 10)
2. At the bottom of the set is a Object[] Array
3. ArrayList Aggregate expansion
Of original capacity 1.5 times
ArrayList At the bottom of the set is an array , How to optimize the ?
As little expansion as possible , Because the efficiency of array expansion is low , It is recommended to use ArrayList The number of elements is estimated before the collection , Given an initial capacity .
4. Array advantages : High retrieval efficiency
5. Array disadvantages : The efficiency of random addition and deletion of elements is low , And arrays can't store large amounts of data ( It's hard to find a large, continuous storage space )
6. Add element to end of array , It's very efficient , Unaffected
7. interview : In so many collections , Which set do you use the most ?
answer :ArrayList aggregate , Because adding elements to the end of the array is not affected by efficiency , in addition , We search for / There are many operations to find an element .
8.ArrayList Collection is not thread safe
package se3.list;
import java.util.ArrayList;
import java.util.List;
public class ArrayListTest01 {
public static void main(String[] args) {
// The default initialization capacity is 10
List list1 = new ArrayList<>();
System.out.println(list1.size());//0
// Specify initialization capacity :20( The length of the array is 20)
List list2 = new ArrayList(20);
// A collection of size() The method is to get the number of elements in the current collection , It's not getting the capacity of the collection
System.out.println(list2.size());//0
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
list1.add(5);
list1.add(6);
list1.add(7);
list1.add(8);
list1.add(9);
list1.add(10);
System.out.println(list1.size());
// Add another element
list1.add(11);
// Here the capacity is expanded to the original 1.5 times ( Automatic expansion )
System.out.println(list1.size());//11
}
}
Construction method
  1. new ArrayList();
  2. new ArrayList(20);
package se3.list;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
// aggregate ArrayList Construction method of
public class ArrayListTest02 {
public static void main(String[] args) {
// Default initialization capacity 10
List myList1 = new ArrayList();
// Specify initialization capacity 100
List myList2 = new ArrayList(100);
// Create a HashSet aggregate
Collection c = new HashSet();
// Add elements to Set aggregate
c.add(100);
c.add(200);
c.add(900);
c.add(50);
// Through this construction method, we can make HashSet Set to List aggregate
List myList3 = new ArrayList(c);
for (int i = 0; i < myList3.size(); i++) {
System.out.println(myList3.get(i));
}
/* Running results :
50
100
900
200
*/
}
}

One way linked list data structure

For linked list data structures : The basic unit is the node Node

For a one-way linked list , Any node Node There are two properties in :

  1. Stored data
  2. The memory address of the next node
One way linked list diagram

Add element diagram

Delete the element diagram

The advantages and disadvantages of linked list
  1. advantage : The efficiency of random addition and deletion of elements is high .( Because adding and deleting elements does not involve a large number of element displacements ). If you encounter more business in random add and delete elements in the collection , It is recommended to use LinkedList.
  2. shortcoming : Query efficiency is low , Every time you look for an element, you need to traverse from the node down .

ArrayList: Bring the retrieval to the extreme

LinkedList: Take random additions and deletions to the extreme

package se3.list;
import java.util.LinkedList;
import java.util.List;
public class LinkedListTest01 {
public static void main(String[] args) {
/**
* LinkedList There are subscripts at the bottom of the set
* Be careful :ArrayList The reason is that the retrieval efficiency is relatively high , Not just because of subscripts . Because of the role of the underlying array .
* LinkedList The set still has subscripts , But search for / It's inefficient to find an element , Because only one traversal can be done from the node to the other .
*/
List list = new LinkedList();
list.add("a");
list.add("b");
list.add("c");
for (int i = 0; i < list.size(); i++) {
Object obj = list.get(i);
System.out.print(obj + " ");
}
// Output results :a b c
}
}

Double linked list and LinkedList aggregate

The basic unit of the bidirectional list is still a node Node

Two way linked list structure

package se3.list;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class LinkedListTest01 {
public static void main(String[] args) {
/**
* LinkedList There are subscripts at the bottom of the set
* Be careful :ArrayList The reason is that the retrieval efficiency is relatively high , Not just because of subscripts . Because of the role of the underlying array .
* LinkedList The set still has subscripts , But search for / It's inefficient to find an element , Because only one traversal can be done from the node to the other .
*/
List list = new LinkedList();
list.add("a");
list.add("b");
list.add("c");
for (int i = 0; i < list.size(); i++) {
Object obj = list.get(i);
System.out.print(obj + " ");
}
// Output results :a b c
/**
* LinkedList Does the collection have initialization capacity ? No,
* Whether it's LinkedList still ArrayList, You don't need to care about which set is it in the future
* Because we're going to be interface oriented programming , The methods that are called are methods in the interface
*/
System.out.println();
List list2 = new ArrayList();// This means that the underlying layer uses an array
//List list2 = new LinkedList();// This means that the underlying layer uses a two-way list
list2.add("123");
list2.add("456");
list2.add("789");
for (int i = 0; i < list2.size(); i++) {
System.out.print(list2.get(i) + " ");
}
// Output results :123 456 789
}
}

Vector aggregate

package se3.list;
import java.util.*;
/**Vector
* 1. The bottom layer is also an array
* 2. Initialize capacity :10
* 3. How to expand the capacity of ?
* Vector The characteristics of set expansion :10-->20-->40-->80
* After the expansion, it will be the original capacity 2 times
* 4.ArrayList Collection expansion features :10-->15-->15*1.5
* ArrayList Expansion is the original capacity 1.5 times
* 5.Vector All methods in are thread synchronized , All carry synchronized keyword
* It's thread safe . Low efficiency , Less used .
*/
public class VectorTest {
public static void main(String[] args) {
// Create a collection
List v = new Vector();
//Vector v = new Vector();
// The default volume 10
v.add(1);
v.add(2);
v.add(3);
v.add(4);
v.add(5);
v.add(6);
v.add(7);
v.add(8);
v.add(9);
v.add(10);
// Expand when it's full ( After the expansion is 20)
v.add(11);
Iterator it = v.iterator();
while (it.hasNext()){
Object object = it.next();
System.out.print(object + " ");
}// Output results ;1 2 3 4 5 6 7 8 9 10 11
/*
How to make a thread unsafe ArrayList Set to thread safe ?
Use the collection utility class :java.util.Collections;
java.util.Collection It's a collection interface
java.util.Collections It's a collection tool class
*/
List mylist = new ArrayList();// Non thread safe
// Become thread safe
Collections.synchronizedList(mylist);
//myList Collections are thread safe
mylist.add("111");
mylist.add("222");
mylist.add("333");
}
}

Generic

The grammatical mechanism of generics , Only works during the compilation phase of the program , Just for the compiler .( Runtime generics are useless )

The advantages of using generics :
  1. The element types stored in the collection are unified
  2. The element type taken from the collection is the type specified by the generic , There's no need for a lot of downward transformation
shortcoming

The disadvantages of generics : Leads to a lack of diversity in the elements stored in the collection !

Be careful : In most businesses , The element types of sets are still uniform .

package se3.collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class GenericTest01 {
public static void main(String[] args) {
// Don't use generic mechanisms , Analysis of the shortcomings of the program
List myList = new ArrayList();
// Prepare for
Cat c = new Cat();
Bird b = new Bird();
// Add objects to the collection
myList.add(c);
myList.add(b);
// Ergodic set , Take out Cat Let her catch mice , Take out Bird Let her fly !
Iterator it = myList.iterator();
while (it.hasNext()){
Object obj = it.next();
// Forced transformation
if (obj instanceof Animal){
Animal a = (Animal)obj;
a.move();
}
if(obj instanceof Cat){
Cat c1 = (Cat)obj;
c1.catMouse();
}
if(obj instanceof Bird){
Bird b1 = (Bird)obj;
b1.fly();
}
}
// Output results :
// Animals are moving !
// The cat is catching mice !
// Animals are moving !
// The birds are flying !
}
}
class Animal{
// Method of parent class
public void move(){
System.out.println(" Animals are moving !");
}
}
class Cat extends Animal{
// Unique method
public void catMouse(){
System.out.println(" The cat is catching mice !");
}
}
class Bird extends Animal{
// Unique method
public void fly(){
System.out.println(" The birds are flying !");
}
}
package se3.collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class GenericTest02 {
public static void main(String[] args) {
// Use generics List<Animal2> after , Express List Only storage is allowed in the collection Animal Data of type
// Specifies the data type of data stored in the collection with a generic type
List<Animal2> myList2 = new ArrayList<Animal2>();
// Appoint list Collection can only store Animal
//myList2.add("abc"); Report errors
Cat2 c2 = new Cat2();
Bird2 b2 = new Bird2();
myList2.add(c2);
myList2.add(b2);
// Acquisition iterator
// This represents iterator iteration Animal type
Iterator<Animal2> it2 = myList2.iterator();
while (it2.hasNext()){
// After using generics , The data type returned by each iteration is Animal type
Animal2 a2 = it2.next();
// If used directly Animal type , There is no need to cast , Call directly
//a2.move();
if(a2 instanceof Cat2){
Cat2 x = (Cat2)a2;
x.catMouse();
}
if (a2 instanceof Bird2){
Bird2 y = (Bird2)a2;
y.fly();
}
}
// Output results :
// The cat is catching mice !
// The birds are flying !
}
}
class Animal2{
// Method of parent class
public void move(){
System.out.println(" Animals are moving !");
}
}
class Cat2 extends Animal2{
// Unique method
public void catMouse(){
System.out.println(" The cat is catching mice !");
}
}
class Bird2 extends Animal2{
// Unique method
public void fly(){
System.out.println(" The birds are flying !");
}
}
Automatic type inference

JDK8 And then introduced : Automatic type inference mechanism ( Also known as the diamond expression )

package se3.collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class GenericTest03 {
public static void main(String[] args) {
//ArrayList< The type here automatically infers , Premise is JDK8 After that >
// Automatic type inference
//List<Animal2> myList3 = new ArrayList<Animal2>();
List<Animal2> myList3 = new ArrayList<>();
myList3.add(new Animal2());
myList3.add(new Cat2());
myList3.add(new Bird2());
// Traverse
Iterator<Animal2> it3 = myList3.iterator();
while (it3.hasNext()){
Animal2 aa = it3.next();
aa.move();
}
List<String> stringList = new ArrayList<>();
// Type mismatch
//stringList.add(new Cat2());
//stringList.add(123);
stringList.add("http://www.163.com");
stringList.add("http://www.baidu.com");
stringList.add("http://www.bjpownode.com");
Iterator<String> its = stringList.iterator();
while (its.hasNext()){
String s = its.next();
String newString = s.substring(7);
System.out.println(newString);
}
/**
* Running results :
* Animals are moving !
* Animals are moving !
* Animals are moving !
* www.163.com
* www.baidu.com
* www.bjpownode.com
*/
}
}
Custom generics

When you customize generics ,<>( Angle brackets ) In is an identifier , Write casually

java The source code often appears in and
1.E yes Element Word initials
2.T yes Type Word initials

package se3.collection;
public class GenericTest04< The identifier can be written casually > {
public void doSome( The identifier can be written casually o){
System.out.println(o);
}
public static void main(String[] args) {
GenericTest04<String> gt = new GenericTest04<>();
//gt.doSome(100); Report errors : Type mismatch
gt.doSome("qwq");// Output qwq
//==========================================
GenericTest04<Integer> gt2 = new GenericTest04<>();
//gt2.doSome(" APO "); Report errors : Type mismatch
gt2.doSome(100);// Output 100
MyIterator<String> mi = new MyIterator<>();
String s1 = mi.get();
//Animal aaa2 = mi2.get(); Report errors
MyIterator<Animal> mi2 = new MyIterator<>();
Animal aaa = mi2.get();
//String s2 = mi2.get(); Report errors
// Without generics, it's just Object type
GenericTest04 gt3 = new GenericTest04();
gt3.doSome(new Object());
gt3.doSome(200);
gt3.doSome(" APO ");
}
}
class MyIterator<T>{
public T get(){
return null;
}
}

Use together foreach

package se3.collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ForEachTest01 {
public static void main(String[] args) {
// establish List aggregate
List<String> stringList = new ArrayList<>();
// Additive elements
stringList.add("hello");
stringList.add(" APO ");
stringList.add("123");
// Traverse , Using the iterator approach
Iterator<String> it = stringList.iterator();
while (it.hasNext()){
String s = it.next();
System.out.print(s + " ");
}
System.out.println();
// Using subscripts ( Only for sets with subscripts )
for (int i = 0; i < stringList.size(); i++) {
System.out.print(stringList.get(i) + " ");
}
System.out.println();
// Use foreach
for (String s : stringList) {// Because generics use Sting type , So it is String s
System.out.print(s + " ");
}
System.out.println();
List<Integer> list = new ArrayList<>();
list.add(100);
list.add(200);
list.add(300);
for (Integer i : list){//i Represents the elements in the set
System.out.print(i + " ");
}
/**
* Output results :
* hello APO 123
* hello APO 123
* hello APO 123
* 100 200 300
*/
}
}
版权声明
本文为[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课程百度云