当前位置:网站首页>Dark horse notes - collection (common methods and traversal methods of collection)
Dark horse notes - collection (common methods and traversal methods of collection)
2022-06-30 12:48:00 【Xiaofu knocks the code】
Catalog
1.2 The systematic characteristics of the set
Collection support for generics
1.3Collection Set commonly used API
1.4Collection The traversal of a set
Mode two :foreach/ enhance for loop
1.5Collection Collection stores objects of custom types
1. aggregate
1.1 Overview of sets
Collections and arrays are containers .
After the array definition is completed and started , Type determination 、 Fixed length , It is suitable for the business scenario determined by the number and type of elements , It is not suitable for adding or deleting data .
Set characteristics
The size of the collection is not fixed , It can change dynamically after startup , The type can also be selected as unfixed . The collection is more like a balloon .
Collection is very suitable for adding and deleting elements .
1. The number of elements stored in arrays and collections .
After the array is defined, the type is determined , Fixed length
The collection type may not be fixed , The size is variable .
2. The type of array and collection storage elements .
Arrays can store data of basic types and reference types .
A collection can only store data that references a data type .
3. Arrays and collections are suitable for the scene .
Array is suitable for the scenario of determining the number and type of data .
The set is suitable for data with uncertain number , And the scene of adding and deleting elements .
1.2 The systematic characteristics of the set

Collection Single column set , Every element ( data ) Contains only one value .
Map Double column set , Each element contains two values ( Key value pair ).

Collection Set features
List Series collection : The added elements are ordered 、 repeatable 、 There is an index .
ArrayList、LinekdList : Orderly 、 repeatable 、 There is an index .
Set Series collection : The added elements are unordered 、 No repetition 、 No index .
HashSet: disorder 、 No repetition 、 No index ;LinkedHashSet: Orderly 、 No repetition 、 No index .
TreeSet: Sort in ascending order by default size 、 No repetition 、 No index .
Collection support for generics
Collections support generics , You can restrict a collection to operate on only one data type at compile time
Be careful : Both collections and generics can only support reference data types , Basic data types are not supported , So the elements stored in the collection are considered objects .
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
/**
The goal is : clear Collection Characteristics of set system
*/
public class CollectionDemo1 {
public static void main(String[] args) {
// Orderly repeatable There is an index
Collection list = new ArrayList();
list.add("Java");
list.add("Java");
list.add("Mybatis");
list.add(23);
list.add(23);
list.add(false);
list.add(false);
System.out.println(list);
// disorder No repetition No index
Collection list1 = new HashSet();
list1.add("Java");
list1.add("Java");
list1.add("Mybatis");
list1.add(23);
list1.add(23);
list1.add(false);
list1.add(false);
System.out.println(list1);
System.out.println("-----------------------------");
// Collection<String> list2 = new ArrayList<String>();
Collection<String> list2 = new ArrayList<>(); // JDK 7 The following type declaration may not be written after the start
list2.add("Java");
// list2.add(23);
list2.add("zhangsan");
// Collections and generics do not support basic data types , Only reference data types are supported
// Collection<int> list3 = new ArrayList<>();
Collection<Integer> list3 = new ArrayList<>();
list3.add(23);
list3.add(233);
list3.add(2333);
Collection<Double> list4 = new ArrayList<>();
list4.add(23.4);
list4.add(233.0);
list4.add(233.3);
}
}
summary :
1. The representative of the collection is ?
Collection Interface .
2.Collection Where is the collection divided 2 A commonly used set system ?
List Series collection : The added elements are ordered 、 repeatable 、 There is an index .
Set Series collection : The added elements are unordered 、 No repetition 、 No index .
3. How to agree on the type of data stored in a collection , What to pay attention to ?
Collections support generics .
Collections and generics do not support basic types , Only reference data types are supported .
1.3Collection Set commonly used API
Collection aggregate
Collection Is the ancestral interface of a single column set , Its function is that all single column sets can be inherited and used .
Collection API as follows :

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
/**
The goal is :Collection Common for collections API.
Collection Is the ancestor class of the collection , Its function is that all collections can be inherited and used , So learn it .
Collection API as follows :
- public boolean add(E e): Add the given object to the current collection .
- public void clear() : Empty all elements in the collection .
- public boolean remove(E e): Delete the given object in the current collection .
- public boolean contains(Object obj): Determine whether the current collection contains the given object .
- public boolean isEmpty(): Determine whether the current set is empty .
- public int size(): Returns the number of elements in the collection .
- public Object[] toArray(): Put the elements in the set , Store in array .
Summary :
Remember the above API.
*/
public class CollectionDemo {
public static void main(String[] args) {
// HashSet: The added elements are unordered , No repetition , No index .
Collection<String> c = new ArrayList<>();
// 1. Additive elements , Add successfully, return true.
c.add("Java");
c.add("HTML");
System.out.println(c.add("HTML"));
c.add("MySQL");
c.add("Java");
System.out.println(c.add(" Dark horse "));
System.out.println(c); // [Java, HTML, HTML, MySQL, Java, Dark horse ]
// 2. Empty the elements of the collection .
// c.clear();
// System.out.println(c);
// 3. Determines if the set is empty Is null and returns true, conversely .
// System.out.println(c.isEmpty());
// 4. Get the size of the collection .
System.out.println(c.size());
// 5. Determine whether an element is included in the collection .
System.out.println(c.contains("Java")); // true
System.out.println(c.contains("java")); // false
System.out.println(c.contains(" Dark horse ")); // true
// 6. Delete an element : If there are multiple duplicate elements, delete the first one by default !
System.out.println(c.remove("java")); // false
System.out.println(c);
System.out.println(c.remove("Java")); // true
System.out.println(c);
// 7. Converting sets into arrays [HTML, HTML, MySQL, Java, Dark horse ]
Object[] arrs = c.toArray();
System.out.println(" Array :" + Arrays.toString(arrs));
System.out.println("---------------------- expand ----------------------");
Collection<String> c1 = new ArrayList<>();
c1.add("java1");
c1.add("java2");
Collection<String> c2 = new ArrayList<>();
c2.add(" Zhao Min ");
c2.add(" YanSuSu ");
// addAll hold c2 Pour all the elements of the collection into c1 In the middle .
c1.addAll(c2);
System.out.println(c1);
System.out.println(c2);
}
}1.4Collection The traversal of a set
Mode one : iterator
Iterator traversal Overview
Traversal is to access the elements in the container one by one .
Iterator in Java The representative of is Iterator, Iterators are specialized ways of traversing collections .
Collection Collection get iterator

Iterator Common methods in

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
The goal is :Collection The traversal of a set .
What is traversal ? Why should we traverse in development ?
Traversal is to access the elements in the container one by one .
It is often necessary to count the sum of elements in development , Find the best value , To find out a certain data and then kill the business, you need to traverse .
Collection The traversal method of a set is that all sets can be used directly , So we learn it .
Collection There are three ways to traverse a collection :
(1) iterator .
(2)foreach( enhance for loop ).
(3)JDK 1.8 New technology after the start Lambda expression ( understand )
a. Iterators traverse the collection .
-- Method :
public Iterator iterator(): Get the iterator corresponding to the collection , Used to traverse elements in a collection
boolean hasNext(): Determine if there is the next element , There is a return true , conversely .
E next(): Get the next element value !
-- technological process :
1. First get the iterator of the current collection
Iterator<String> it = lists.iterator();
2. Define a while loop , Ask once, take once .
adopt it.hasNext() Ask if there is a next element , Have passed
it.next() Take the next element .
Summary :
Remember the code .
*/
public class CollectionDemo01 {
public static void main(String[] args) {
ArrayList<String> lists = new ArrayList<>();
lists.add(" Zhao Min ");
lists.add(" Small zhao ");
lists.add(" Morpheme ");
lists.add(" extinction ");
System.out.println(lists);
// [ Zhao Min , Small zhao , Morpheme , extinction ]
// it
// 1、 Gets the iterator object of the current collection .
Iterator<String> it = lists.iterator();
// String ele = it.next();
// System.out.println(ele);
// System.out.println(it.next());
// System.out.println(it.next());
// System.out.println(it.next());
// System.out.println(it.next()); // NoSuchElementException An error occurred without this element exception
// 2、 Definition while loop
while (it.hasNext()){
String ele = it.next();
System.out.println(ele);
}
System.out.println("-----------------------------");
}
}Iterator execution process

summary :
1. Where is the default location of the iterator .
Iterator<E> iterator(): Get the iterator object , The default index to the current collection 0.
2. What happens if the iterator takes elements out of bounds .
There will be NoSuchElementException abnormal .
Mode two :foreach/ enhance for loop
enhance for loop : You can traverse either a collection or an array .

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
public class CollectionDemo02 {
public static void main(String[] args) {
Collection<String> lists = new ArrayList<>();
lists.add(" Zhao Min ");
lists.add(" Small zhao ");
lists.add(" YanSuSu ");
lists.add(" Zhou Zhiruo ");
System.out.println(lists);
// [ Zhao Min , Small zhao , YanSuSu , Zhou Zhiruo ]
// ele
for (String ele : lists) {
System.out.println(ele);
}
System.out.println("------------------");
double[] scores = {100, 99.5 , 59.5};
for (double score : scores) {
System.out.println(score);
// if(score == 59.5){
// score = 100.0; // Modification is meaningless , It will not affect the element value of the array .
// }
}
System.out.println(Arrays.toString(scores));
}
}Mode three :lambda expression
Lambda Expression traversal set
Thanks to the JDK 8 Start new technology Lambda expression , Provides a simpler 、 More direct way to traverse the collection .
Collection combination Lambda Ergodic API


import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Consumer;
public class CollectionDemo03 {
public static void main(String[] args) {
Collection<String> lists = new ArrayList<>();
lists.add(" Zhao Min ");
lists.add(" Small zhao ");
lists.add(" YanSuSu ");
lists.add(" Zhou Zhiruo ");
System.out.println(lists);
// [ Zhao Min , Small zhao , YanSuSu , Zhou Zhiruo ]
// s
lists.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
});
// lists.forEach(s -> {
// System.out.println(s);
// });
// lists.forEach(s -> System.out.println(s) );
lists.forEach(System.out::println );
}
}
1.5Collection Collection stores objects of custom types
Case study : The representation of film information in the program
demand : A cinema system needs to store the above three movies in the background , Then show it in turn .
analysis :
1. Define a movie class , Define a collection to store movie objects .
2. establish 3 A movie object , Encapsulate relevant data , hold 3 An object is stored in the collection .
3. Traverse the collection of 3 Objects , Output relevant information .
public class Movie {
private String name;
private double score;
private String actor;
public Movie() {
}
public Movie(String name, double score, String actor) {
this.name = name;
this.score = score;
this.actor = actor;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public String getActor() {
return actor;
}
public void setActor(String actor) {
this.actor = actor;
}
@Override
public String toString() {
return "Movie{" +
"name='" + name + '\'' +
", score=" + score +
", actor='" + actor + '\'' +
'}';
}
}
import java.util.ArrayList;
import java.util.Collection;
public class TestDemo {
public static void main(String[] args) {
// 1、 Define a movie class
// 2、 Define a collection object to store 3 The object of the film
Collection<Movie> movies = new ArrayList<Object>();
movies.add(new Movie("《 Hello , Li Huanying 》", 9.5, " Zhang Xiaofei , Jia Ling , Shen Tang , Chen He "));
movies.add(new Movie("《 Chinatown detective 》", 8.5, " Baoqiang Wang , Liu Haoran , beauty "));
movies.add(new Movie("《 Assassinate a novelist 》",8.6, " Lei Jia Yin , Yang Mi "));
System.out.println(movies);
// 3、 Traverse each movie object in the collection container
for (Movie movie : movies) {
System.out.println(" title :" + movie.getName());
System.out.println(" score :" + movie.getScore());
System.out.println(" starring :" + movie.getActor());
}
}
}
What is stored in the collection is the address of the element object .
边栏推荐
- 黑马笔记---常用日期API
- 数据仓库建设之确定主题域
- 黑马笔记---包装类,正则表达式,Arrays类
- SuperMap 3D SDKs_ Unity plug-in development - connect data services for SQL queries
- pyqt5界面的布局与资源文件的载入
- LeetCode_栈_中等_227.基本计算器 II(不含括号)
- [QNX Hypervisor 2.2用户手册]6.2.3 Guest与外部之间通信
- 基于ThinkPHP5封装tronapi-波场接口-PHP版本--附接口文档-20220627
- Q-learning notes
- Idea has a new artifact, a set of code to adapt to multiple terminals!
猜你喜欢

腾讯二面:@Bean 与 @Component 用在同一个类上,会怎么样?

Flinksql customizes udatf to implement topn

Visual studio configures QT and implements project packaging through NSIS
![[one day learning awk] Fundamentals](/img/09/a3eb03066eb063bd8594065cdce0aa.png)
[one day learning awk] Fundamentals

Dqn notes

NoSQL - redis configuration and optimization

Browser plays RTSP video based on nodejs
![[learn awk in one day] operator](/img/52/fd476d95202f3a956fd59437c2d960.png)
[learn awk in one day] operator

FlinkSQL自定义UDAF使用的三种方式

【一天学awk】正则匹配
随机推荐
Discussion on JMeter operation principle
STM32 移植 RT-Thread 标准版的 FinSH 组件
Mysql中 begin..end使用遇到的坑
Redis - problèmes de cache
Charles打断点修改请求数据&响应数据
电机控制Clarke(α/β)等幅值变换推导
JMeter's performance test process and performance test focus
"Xiaodeng" user personal data management in operation and maintenance
Android development interview real question advanced version (with answer analysis)
How to use the plug-in mechanism to gracefully encapsulate your request hook
SQLSERVER 查询编码是 936 简体中文GBK,那我是写936 还是写GBK?
Introduction to the novelty of substrate source code: comprehensive update of Boca system Boca weight calculation, optimization and adjustment of governance version 2.0
Introduction to sub source code updating: mid May: uniques NFT module and nomination pool
After the market value evaporated by 65billion yuan, the "mask king" made steady medical treatment and focused on condoms
Some commonly used hardware information of the server (constantly updated)
Substrate 源码追新导读: Pallet Alliance 并入主线,
两批次纯牛奶不合格?麦趣尔回应:正对产品大批量排查抽检
Spatiotemporal prediction 2-gcn_ LSTM
解决numpy.core._exceptions.UFuncTypeError: ufunc ‘add‘ did not contain a loop with signature matchin问题
Shell编程概述