当前位置:网站首页>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 .
边栏推荐
- Tencent cloud Database Engineer competency certification was launched, and people from all walks of life talked about talent training problems
- 【OpenGL】OpenGL Examples
- “\“id\“ contains an invalid value“
- SQLSERVER 查询编码是 936 简体中文GBK,那我是写936 还是写GBK?
- Sarsa notes
- Determining the subject area of data warehouse construction
- Tencent two sides: @bean and @component are used on the same class. What happens?
- Unity脚本程序的开发
- Instructions for legend use in SuperMap iclient3d 11i for cesium 3D scene
- Flink sql控制台,不识别group_concat函数吗?
猜你喜欢

Dark horse notes -- List series collections and generics

Dark horse notes -- wrapper class, regular expression, arrays class

Three ways for flinksql to customize udaf

FlinkSQL自定义UDTF使用的四种方式
![[one day learning awk] Fundamentals](/img/09/a3eb03066eb063bd8594065cdce0aa.png)
[one day learning awk] Fundamentals

60 个神级 VS Code 插件!!

【惊了】迅雷下载速度竟然比不上虚拟机中的下载速度
![[yitianxue awk] regular matching](/img/a6/608ec8d0808dfae04d19dfeea66399.png)
[yitianxue awk] regular matching

rpm2rpm 打包步骤

How to select an OLAP database engine?
随机推荐
Double dqn notes
JMeter之事务控制器
Sublist3r error reporting solution
elementui中清除tinymce富文本缓存
Dataworks synchronizes maxcomputer to sqlserver. Chinese characters become garbled. How can I solve it
Substrate 源码追新导读: Pallet Alliance 并入主线,
Scratch drawing square electronic society graphical programming scratch grade examination level 2 true questions and answers analysis June 2022
【300+精选大厂面试题持续分享】大数据运维尖刀面试题专栏(二)
JMeter性能测试工作中遇到的问题及剖析,你遇到了几个?
【一天学awk】基础中的基础
第十三章 信号(三)- 示例演示
Inner join and outer join of MySQL tables
Why should offline stores do new retail?
kubeedge的核心理念
[one day learning awk] use of built-in variables
Clipboardjs - development learning summary 1
rpm2rpm 打包步骤
Redis cache problem
【OpenGL】OpenGL Examples
【一天学awk】运算符