当前位置:网站首页>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 .
边栏推荐
- [one day learning awk] use of built-in variables
- Clipboardjs - development learning summary 1
- ffmpeg 杂项
- SQLSERVER 查询编码是 936 简体中文GBK,那我是写936 还是写GBK?
- Qt中的数据库使用
- Redis-缓存问题
- Videos are stored in a folder every 100 frames, and pictures are transferred to videos after processing
- 黑马笔记---List系列集合与泛型
- Idea has a new artifact, a set of code to adapt to multiple terminals!
- 腾讯二面:@Bean 与 @Component 用在同一个类上,会怎么样?
猜你喜欢
Dark horse notes - common date API
[one day learning awk] use of built-in variables
60 divine vs Code plug-ins!!
如何利用AI技术优化独立站客服系统?听听专家怎么说!
SuperMap iclient3d for webgl loading TMS tiles
Shell编程概述
[yitianxue awk] regular matching
【300+精选大厂面试题持续分享】大数据运维尖刀面试题专栏(二)
Instructions for legend use in SuperMap iclient3d 11i for cesium 3D scene
Wechat launched the picture big bang function; Apple's self-developed 5g chip may have failed; Microsoft solves the bug that causes edge to stop responding | geek headlines
随机推荐
电机控制park变换公式推导
[one day learning awk] Fundamentals
Qt中的数据库使用
【C语言深度解剖】float变量在内存中存储原理&&指针变量与“零值”比较
JMeter之性能测试流程及性能测试关注点
After the market value evaporated by 65billion yuan, the "mask king" made steady medical treatment and focused on condoms
Unity脚本的基础语法(1)-游戏对象的常用操作
市值蒸发650亿后,“口罩大王”稳健医疗,盯上了安全套
Flink sql控制台,不识别group_concat函数吗?
Illustration creating a stored procedure using Navicat for MySQL
Substrate 源码追新导读: Call调用索引化, 存储层事物化全面完成
Database usage in QT
Introduction to the novelty of substrat source code: indexing of call calls and fully completing the materialization of storage layer
Problems and analysis in JMeter performance testing. How many problems have you encountered?
Unity的脚本的基础语法(2)-Unity中记录时间
[one day learning awk] array usage
Redis installation on Linux system
MySQL中变量的定义和变量的赋值使用
Substrate 源码追新导读: Pallet Alliance 并入主线,
Tronapi-波场接口-源码无加密-可二开--附接口文档-基于ThinkPHP5封装-作者详细指导-2022年6月29日21:59:34