openharmony 鸿蒙 arkts-collections-introduction

2025-06-06 浏览 (1)

Shared Container

ArkTS Collections

ArkTS shared containers (@arkts.collections (ArkTS Collections)) are designed for high-performance data transmission between concurrent tasks. They offer similar functionality to the containers defined in the ECMAScript 262 specification but with some key differences, which are outlined in the Behavior Differences Between Shared Container APIs and Native APIs.

By default, ArkTS shared containers are passed by reference, allowing multiple concurrent tasks to manipulate the same container instance. They also support pass-by-copy, where each concurrent task holds an ArkTS container instance.

ArkTS shared containers are not thread-safe and employ a fail-fast mechanism to prevent concurrent structural modifications, which would otherwise trigger exceptions. When modifying container properties, you must use the asynchronous lock mechanism to ensure safe access.

The ArkTS shared containers include the following types: Array, Map, Set, TypedArray (Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Uint8ClampedArray, and Float32Array), and ArrayBuffer. For details, see @arkts.collections (ArkTS Collections).

The following is an example of using the collection:

import { ArkTSUtils, collections, taskpool } from '@kit.ArkTS';

@Concurrent
async function add(arr: collections.Array<number>, lock: ArkTSUtils.locks.AsyncLock) {
 await lock.lockAsync(() => {  // Without the asynchronous lock, the task will fail due to data race conflicts.
   arr[0]++;
 })
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    RelativeContainer() {
      Text(this.message)
        .id('HelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(() => {
          let taskGroup = new taskpool.TaskGroup();
          let lock = new ArkTSUtils.locks.AsyncLock();
          let arr = collections.Array.create<number>(1, 0);
          let count = 1000;
          while (count--) {
            taskGroup.addTask(add, arr, lock);
          }
          taskpool.execute(taskGroup).then(() => {
            console.info(`Return success: ${arr[0]} === ${count}`);
          }).catch((e: Error) => {
            console.error("Return error.");
          })
        })
    }
    .height('100%')
    .width('100%')
  }
}

Behavior Differences Between Shared Container APIs and Native APIs

ArkTS provides shared containers for Sendable data, with some behavior differences when compared with native APIs. These differences are detailed below.

NOTE

ArkTS shared containers have different types from native ECMAScript containers. Therefore, if the native isArray() method is used on a collections.Array instance object, false is returned.

Array

Native Array containers can be converted into ArkTS Array containers using the collections.Array.from method, and ArkTS Array containers can be converted into native Array containers using the native from method.

Native APIArkTS Collections APIBehavior Difference ExistsDifferent Behavior in ArkTS Collections
length: numberreadonly length: numberYesTo prevent the spread of undefined, it is not allowed to set length.
new(arrayLength ?: number): any[]static create(arrayLength: number, initialValue: T): ArrayYesTo prevent the spread of undefined, a constructor must be provided with an initial value.
new <T>(arrayLength: number): T[]constructor()No/
new <T>(...items: T[]): T[]constructor(first: T, ...left: T[])YesTo prevent the spread of undefined, a constructor must be provided with an initial value. In inheritance scenarios, this constructor cannot be called to construct an object.
from<T>(arrayLike: ArrayLike<T>): T[]static from<T>(arrayLike: ArrayLike<T>): Array<T>No/
pop(): T |undefinedpop(): T |undefinedYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
push(...items: T[]): numberpush(...items: T[]): numberYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
concat(...items: ConcatArray<T>[]): T[]concat(...items: ConcatArray<T>[]): Array<T>YesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
concat(...items: (T |ConcatArray<T>)[]): T[]concat(...items: ConcatArray<T>[]): Array<T>YesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
join(separator?: string): stringjoin(separator?: string): stringNo/
shift(): T |undefinedshift(): T |undefinedYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
slice(start?: number, end?: number): T[]slice(start?: number, end?: number): Array<T>No/
sort(compareFn?: (a: T, b: T) => number): thissort(compareFn?: (a: T, b: T) => number): Array<T>Yes1. It is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
2. In inheritance scenarios, the actual type of the return value cannot be obtained.
unshift(...items: T[]): numberunshift(...items: T[]): numberYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
indexOf(searchElement: T, fromIndex?: number): numberindexOf(searchElement: T, fromIndex?: number): numberNo/
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): voidforEach(callbackFn: (value: T, index: number, array: Array<T>) => void): voidYesArkTS does not support this. As a result, the thisArg parameter is not supported.
map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]map<U>(callbackFn: (value: T, index: number, array: Array<T>) => U): Array<U>YesArkTS does not support this. As a result, the thisArg parameter is not supported.
filter(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[]filter(predicate: (value: T, index: number, array: Array<T>) => boolean): Array<T>YesArkTS does not support this. As a result, the thisArg parameter is not supported.
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): Treduce(callbackFn: (previousValue: T, currentValue: T, currentIndex: number, array: Array<T>) => T): TNo/
reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): Ureduce<U>(callbackFn: (previousValue: U, currentValue: T, currentIndex: number, array: Array<T>) => U, initialValue: U): UNo/
[n: number]: T[index: number]: TYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
findIndex(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): numberfindIndex(predicate: (value: T, index: number, obj: Array<T>) => boolean): numberYesArkTS does not support this. As a result, the thisArg parameter is not supported.
fill(value: T, start?: number, end?: number): thisfill(value: T, start?: number, end?: number): Array<T>Yes1. It is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
2. In inheritance scenarios, the actual type of the return value cannot be obtained.
entries(): IterableIterator<[number, T]>entries(): IterableIterator<[number, T]>No/
keys(): IterableIterator<number>keys(): IterableIterator<number>No/
values(): IterableIterator<T>values(): IterableIterator<T>No/
includes(searchElement: T, fromIndex?: number): booleanincludes(searchElement: T, fromIndex?: number): booleanNo/
at(index: number): T |undefinedat(index: number): T |undefinedNo/

ArrayBuffer

Native APIArkTS Collections APIBehavior Difference ExistsDifferent Behavior in ArkTS Collections
readonly byteLength: numberreadonly byteLength: numberNo/
slice(begin: number, end?: number): ArrayBufferslice(begin: number, end?: number): ArrayBufferNo/
new(byteLength: number): ArrayBufferconstructor(byteLength: number)No/

TypedArray (Int8Array Used as an Example)

Native TypedArray containers can be converted into ArkTS TypedArray containers using the collections.TypedArray.from method, and ArkTS TypedArray containers can be converted into native TypedArray containers using the native from method.

Native APIArkTS Collections APIBehavior Difference ExistsDifferent Behavior in ArkTS Collections
readonly buffer: ArrayBufferLikereadonly buffer: ArrayBufferNo/
readonly byteLength: numberreadonly byteLength: numberNo/
readonly byteOffset: numberreadonly byteOffset: numberNo/
readonly length: numberreadonly length: numberNo/
readonly BYTES_PER_ELEMENT: numberstatic readonly BYTES_PER_ELEMENT: numberNo/
copyWithin(target: number, start: number, end?: number): thiscopyWithin(target: number, start: number, end?: number): Int8ArrayYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
every(predicate: (value: number, index: number, array: Int8Array) => unknown, thisArg?: any): booleanevery(predicate: TypedArrayPredicateFn<number, Int8Array>): booleanYes1. It is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
2. ArkTS does not support this. As a result, the thisArg parameter is not supported.
fill(value: number, start?: number, end?: number): thisfill(value: number, start?: number, end?: number): Int8ArrayYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
filter(predicate: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Arrayfilter(predicate: TypedArrayPredicateFn<number, Int8Array>): Int8ArrayYes1. It is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
2. ArkTS does not support this. As a result, the thisArg parameter is not supported.
find(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number |undefinedfind(predicate: TypedArrayPredicateFn<number, Int8Array>): number |undefinedYes1. It is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
2. ArkTS does not support this. As a result, the thisArg parameter is not supported.
findIndex(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): numberfindIndex(predicate: TypedArrayPredicateFn<number, Int8Array>): numberYesArkTS does not support this. As a result, the thisArg parameter is not supported.
forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): voidforEach(callbackFn: (value: number, index: number, array: Int8Array) => void): voidYes1. It is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
2. ArkTS does not support this. As a result, the thisArg parameter is not supported.
indexOf(searchElement: number, fromIndex?: number): numberindexOf(searchElement: number, fromIndex?: number): numberNo/
join(separator?: string): stringjoin(separator?: string): stringNo/
map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Arraymap(callbackFn: TypedArrayForEachCallback<number, Int8Array>): Int8ArrayYes1. It is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
2. ArkTS does not support this. As a result, the thisArg parameter is not supported.
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): numberreduce(callbackFn: TypedArrayReduceCallback<number, number, Int8Array>): numberNo/
reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): numberreduce(callbackFn: TypedArrayReduceCallback<number, number, Int8Array>, initialValue: number): numberNo/
reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): Ureduce<U>(callbackFn: TypedArrayReduceCallback<U, number, Int8Array>, initialValue: U): UNo/
reverse(): Int8Arrayreverse(): Int8ArrayNo/
set(array: ArrayLike<number>, offset?: number): voidset(array: ArrayLike<number>, offset?: number): voidYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
slice(start?: number, end?: number): Int8Arrayslice(start?: number, end?: number): Int8ArrayNo/
some(predicate: (value: number, index: number, array: Int8Array) => unknown, thisArg?: any): booleansome(predicate: TypedArrayPredicateFn<number, Int8Array>): booleanYesArkTS does not support this. As a result, the thisArg parameter is not supported.
sort(compareFn?: (a: number, b: number) => number): thissort(compareFn?: TypedArrayCompareFn<number>): Int8ArrayYes1. It is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
2. In inheritance scenarios, the actual type of the return value cannot be obtained.
subarray(begin?: number, end?: number): Int8Arraysubarray(begin?: number, end?: number): Int8ArrayYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
[index: number]: number[index: number]: numberYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
entries(): IterableIterator<[number, number]>entries(): IterableIterator<[number, number]>No/
keys(): IterableIterator<number>keys(): IterableIterator<number>No/
values(): IterableIterator<number>values(): IterableIterator<number>No/
includes(searchElement: number, fromIndex?: number): booleanincludes(searchElement: number, fromIndex?: number): booleanNo/
at(index: number): number |undefinedat(index: number): number |undefinedNo/
new(length: number): Int8Arrayconstructor(length: number)No/
new(array: ArrayLike<number> |ArrayBufferLike): Int8Arrayconstructor(array: ArrayLike<number> |ArrayBuffer)No/
new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Arrayconstructor(buffer: ArrayBuffer, byteOffset?: number, length?: number)No/
from(arrayLike: ArrayLike<number>): Int8Arraystatic from(arrayLike: ArrayLike<number>): Int8ArrayNo/
from<T>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any): Int8Arraystatic from<T>(arrayLike: ArrayLike<T>, mapFn: TypedArrayFromMapFn<T, number>): Int8ArrayYesArkTS does not support this. As a result, the thisArg parameter is not supported.
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Arraystatic from(arrayLike: Iterable<number>, mapFn?: TypedArrayFromMapFn<number, number>): Int8ArrayYesArkTS does not support this. As a result, the thisArg parameter is not supported.

Map

Native APIArkTS Collections APIBehavior Difference ExistsDifferent Behavior in ArkTS Collections
readonly size: numberreadonly size: numberYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
clear(): voidclear(): voidYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
delete(key: K): booleandelete(key: K): booleanYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): voidforEach(callbackFn: (value: V, key: K, map: Map<K, V>) => void): voidYes1. It is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
2. ArkTS does not support this. As a result, the thisArg parameter is not supported.
get(key: K): V |undefinedget(key: K): V |undefinedYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
has(key: K): booleanhas(key: K): booleanYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
set(key: K, value: V): thisset(key: K, value: V): Map<K, V>YesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
entries(): IterableIterator<[K, V]>entries(): IterableIterator<[K, V]>No/
keys(): IterableIterator<K>keys(): IterableIterator<K>No/
values(): IterableIterator<V>values(): IterableIterator<V>No/
new <K, V>(entries?: readonly (readonly [K, V])[] |null): Map<K, V>constructor(entries?: readonly (readonly [K, V])[] |null)YesThe passed-in values of k and v during construction cannot be non-Sendable data. Otherwise, an error is reported during compilation.

Set

Native APIArkTS Collections APIBehavior Difference ExistsDifferent Behavior in ArkTS Collections
readonly size: numberreadonly size: numberYesComputed property names (arkts-sendable-compated-prop-name) cannot be used in Sendable classes and interfaces.
add(value: T): thisadd(value: T): Set<T>YesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
clear(): voidclear(): voidYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
delete(value: T): booleandelete(value: T): booleanYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
forEach(callbackfn: (value: T, value2: T, set: Set<T>) => void, thisArg?: any): voidforEach(callbackFn: (value: T, value2: T, set: Set<T>) => void): voidYes1. It is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
2. ArkTS does not support this. As a result, the thisArg parameter is not supported.
has(value: T): booleanhas(value: T): booleanYesIt is not allowed to add, delete, or modify elements during iteration or access. Otherwise, an exception is thrown.
entries(): IterableIterator<[T, T]>entries(): IterableIterator<[T, T]>No/
keys(): IterableIterator<T>keys(): IterableIterator<T>No/
values(): IterableIterator<T>values(): IterableIterator<T>YesComputed property names (arkts-sendable-compated-prop-name) cannot be used in Sendable classes and interfaces.
new <T = any>(values?: readonly T[] |null): Set<T>constructor(values?: readonly T[] |null)YesThe passed-in values during construction cannot be non-Sendable data. Otherwise, an error is reported during compilation.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙ArkTS

harmony 鸿蒙Configuring arkOptions in build-profile.json5

harmony 鸿蒙Asynchronous Lock

harmony 鸿蒙Ark Bytecode File Format

harmony 鸿蒙Naming Conventions for Ark Bytecode Functions

harmony 鸿蒙Ark Bytecode Fundamentals

harmony 鸿蒙Overview of Ark Bytecode

harmony 鸿蒙Asynchronous Waiting

harmony 鸿蒙ArkTS Cross-Language Interaction

harmony 鸿蒙Dynamic Import

  • 所属分类: 后端技术
  • 本文标签: 鸿蒙 软件
  • 版权声明: 本文链接 https://seaxiang.com/blog/QYKn9d