当前位置:网站首页>Collection overview, array encapsulation
Collection overview, array encapsulation
2022-06-25 16:19:00 【weixin_ forty-eight million six hundred and forty-four thousand】
1 Array encapsulation
1.1 demand
It is generally troublesome to operate on arrays , You need to create an array to add and delete , Copy array or element shift
therefore , Encapsulate these additions and deletions
1.2 Realization
public class Array {
// Encapsulated array
private Object[] elements;
// Number of elements in the array
private int size = 0;
public Array(){
// The default array length is 10
elements = new Object[10];
}
// Get the number of elements
public int size(){
return size;
}
// Get data from index
public Object get(int index){
// If index>=size
if (index >= size) {
throw new ArrayIndexOutOfBoundsException(index);
}
return elements[index];
}
/**
* Adding elements to an array
*
* @param element
*/
public void add(Object element) {
// 1 Determine whether the array is full
if (size == elements.length) {
// 1.2 Full of Capacity expansion , Copy the array , Put it in again
// The expansion capacity is twice that of the original
Object[] newArr = new Object[size << 1];
// Array copy
System.arraycopy(elements, 0, newArr, 0, size);
// assignment
elements = newArr;
}
// Add in ,size++
elements[size] = element;
size++;
}
/**
* Deletes the specified element
*
* @param index
*/
public void remove(int index) {
// If index >= size explain non-existent
if (index >= size) {
throw new ArrayIndexOutOfBoundsException(index);
}
// displacement
for (int i = index; i < size - 1; i++) {
elements[index] = elements[index + 1];
}
// The last bit is assigned null
elements[size - 1] = null;
// Number -1
size--;
}
}2 aggregate
2.1 summary Java A collection is a set of data that enables a program to store and manipulate elements that are not fixed . all Java Collection classes are all located in java.util In bag
Be careful : If the basic type is stored in the collection , Be sure to “ Packing ” In correspondence with ” Basic type packaging ”.
Collection Is a collection , The two direct sub interfaces are List and set
List characteristic : Orderly repeatable , Ensure that the data is added in the same order as the data is taken out
Set characteristic : disorder Do not repeat , There is no guarantee that the data is added and taken out in the same order
List There are three subcategories :
ArrayList : At the bottom is an array , Queries and changes are extremely efficient
LinkedList : The bottom layer is a two-way linked list , Adding and deleting are more efficient
Vector : The bottom layer is also an array , Is thread safe , obsolete , It is not recommended to use , Has been ArrayList Instead of
Set There are two subclasses
HashSet : At the bottom is a hash table
TreeSet : At the bottom is a binary tree
arrayList For example
import java.util.ArrayList;
import java.util.Collection;
/**
* Collection Is a collection , The two direct sub interfaces are List and set
List characteristic : Orderly repeatable , Ensure that the data is added in the same order as the data is taken out
Set characteristic : disorder Do not repeat , There is no guarantee that the data is added and taken out in the same order
List There are three subcategories :
ArrayList : At the bottom is an array , Queries and changes are extremely efficient
LinkedList : The bottom layer is a two-way linked list , Adding and deleting are more efficient
Vector : The bottom layer is also an array , Is thread safe , obsolete , It is not recommended to use , Has been ArrayList Instead of
Set There are two subclasses
HashSet : At the bottom is a hash table
TreeSet : At the bottom is a binary tree
Collection , Only uniform data types can be saved , That's it Object, Therefore, basic data types cannot be saved in the collection
Since you can save Object, This means that any type of element can be saved , Because all reference types can be used for Object There is polymorphism
* @ author Dawn Education - Liuchengzhi
* @ Time 2022 year 1 month 18 On the afternoon of Sunday 10:15:59
*/
public class Collection_01 {
public static void main(String[] args) {
// Create a ArrayList object
Collection collection = new ArrayList();
// Determine whether it is null
System.out.println(collection.isEmpty());
// Number of existing elements
System.out.println(collection.size());
// add to , If you add a basic type , Then it will be automatically boxed to the corresponding packaging type , Then polymorphic transformation occurs to Object type
collection.add(1);
collection.add(3);
collection.add(2);
collection.add(" Zhang San ");
System.out.println(collection.size());
System.out.println(collection);
// Deletes the specified element , Be careful It's not an index , Yes delete based on data
collection.remove(" Zhang San ");
System.out.println(collection);
// Convert to array
Object[] arr = collection.toArray();
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
// Clear the data in the collection
collection.clear();
System.out.println(collection.size());
}
}iterator
mport java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* Iterator iterator
* An iterator is a pattern , It can separate the traversed object from the traversed object , We no longer care about the underlying data structure , How to store data
* Just get the iterator object , You can traverse
*
* collection in Provides a iterator() Method Used to get iterator objects
* aggregate .iterator();
*
* In an iterator , There are three ways
* 1 boolean hasNext() : Determine whether there are elements under the cursor , The default point is to the top , It doesn't point to the first element
* 2 E next() : Move the iterator cursor down one bit , And take out the element
* 3 remove () : Delete the currently executed element , Will also delete the in the set
*
* Once the iterator is created , Collection cannot be added or deleted , If you add and delete , Need to regenerate iterators
*
* enhance for loop forEach It's short for iterator
* @ author Dawn Education - Liuchengzhi
* @ Time 2022 year 1 month 18 On the afternoon of Sunday 10:16:40
*/
public class Collection_02 {
public static void main(String[] args) {
// establish
Collection c = new ArrayList();
// add to
c.add(1);
c.add(11);
c.add(12);
c.add(13);
c.add(14);
// Generate iterators
Iterator it = c.iterator();
// After generating the iterator , You can't add or delete , Unless you regenerate
// c.add(14);
while (it.hasNext()) {
Object o = it.next();
System.out.println(o);
}
// After the iterator is used , Want to use again , Need to rebuild , Because the cursor has pointed to the last one
it = c.iterator();
while (it.hasNext()) {
Object o = it.next();
System.out.println(o);
}
}
}2.4foreach
import java.util.ArrayList;
import java.util.Collection;
/**
*
* @ author Dawn Education - Liuchengzhi
* @ Time 2022 year 1 month 18 On the afternoon of Sunday 10:18:23
*/
public class Collection_04 {
public static void main(String[] args) {
int[] arr = {1,2,3};
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
// ------
// Will be able to Every element in the array Assign a value to Variable element Not subscript
for (int element : arr) {
System.out.println(element);
}
Collection c = new ArrayList();
c.add("a");
c.add("b");
c.add("c");
// foreach Short for iterator , So the function is limited , Can only query , Can't delete
// Want to delete... In traversal , That requires an iterator remove
for (Object object : c) {
System.out.println(object);
}
}
}边栏推荐
- LeCun预言AGI:大模型和强化学习都是斜道!我的「世界模型」才是新路
- ES6 deconstruction assignment rename
- 深度学习 pytorch cifar10数据集训练「建议收藏」
- 10 Super VIM plug-ins, I can't put them down
- 面试官:你简历上说精通mysql,那你说下聚簇/联合/覆盖索引、回表、索引下推
- What are some tricks that novice programmers don't know?
- Flutter textfield setting can input multiple lines
- 地理位置数据存储方案——Redis GEO
- What plug-ins are available for vscade?
- 教务系统开发(PHP+MySQL)
猜你喜欢

Beginner bug set

error Parsing error: Unexpected reserved word ‘await‘.

iVX低代码平台系列详解 -- 概述篇(一)

Go language - lock operation

The release of autok3s v0.5.0 continues to be simple and friendly

不要小看了积分商城,它的作用可以很大!

Principle analysis of ThreadLocal source code

Overall MySQL architecture and statement execution process

Blue Bridge Cup - practice system login

The paid video at station B caused the up master to lose more than ten thousand fans
随机推荐
Practice of geospatial data in Nepal graph
一行代码可以做什么?
转换Cifar10数据集
ES6 deconstruction assignment rename
In the wechat environment, H5 jumps to the specified page of the applet
The paid video at station B caused the up master to lose more than ten thousand fans
TFIDF and BM25
地理位置数据存储方案——Redis GEO
leetcode-8. 字符串转换整数 (atoi)
f_ Read function [easy to understand]
What is the NFT digital collection?
MT60B1G16HC-48B:A美光内存颗粒FBGA代码D8BNK[通俗易懂]
赫尔辛基交通安全改善项目部署Velodyne Lidar智能基础设施解决方案
Tensorflow loading cifar10 dataset
Shuttle pop-up returns to the upper level
[issue 24] one year experience of golang to develop futu
Uniapp converts graphic verification codes in the form of file streams into images
深度学习 pytorch cifar10数据集训练「建议收藏」
Go development team technical leader Russ Cox sends a document to share go's version control history
普通人的2022春招总结(阿里、腾讯offer)