編程語言對比系列:二、數組的基本使用

文章大綱如下:

一、初始化 init array File URL Array

OC init array File URL

  • 方法
    // 空數組
    + (instancetype)array;
    - (instancetype)init NS_DESIGNATED_INITIALIZER;

    // 通過一個元素構建數組
    + (instancetype)arrayWithObject:(ObjectType)anObject;

    // 通過多個元素構建數組
    + (instancetype)arrayWithObjects:(ObjectType)firstObj, ... NS_REQUIRES_NIL_TERMINATION;
    - (instancetype)initWithObjects:(ObjectType)firstObj, ... NS_REQUIRES_NIL_TERMINATION;

    // 通過其他數組
    + (instancetype)arrayWithArray:(NSArray<ObjectType> *)array;
    - (instancetype)initWithArray:(NSArray<ObjectType> *)array;
    // flag 爲 YES 時進行“深拷貝”
    - (instancetype)initWithArray:(NSArray<ObjectType> *)array copyItems:(BOOL)flag;

    // 通過文件路徑 file 或 url
    // 這兩個方法帶有 error 參數,11.0之後可以使用
    - (nullable NSArray<ObjectType> *)initWithContentsOfURL:(NSURL *)url error:(NSError **)error  API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0));
    + (nullable NSArray<ObjectType> *)arrayWithContentsOfURL:(NSURL *)url error:(NSError **)error API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0)) NS_SWIFT_UNAVAILABLE("Use initializer instead");
    // 下面的方法不帶有 error 參數,後面會被廢棄掉
    + (nullable NSMutableArray<ObjectType> *)arrayWithContentsOfFile:(NSString *)path;
    + (nullable NSMutableArray<ObjectType> *)arrayWithContentsOfURL:(NSURL *)url;
    - (nullable NSMutableArray<ObjectType> *)initWithContentsOfFile:(NSString *)path;
    - (nullable NSMutableArray<ObjectType> *)initWithContentsOfURL:(NSURL *)url;

    // 通過 c 語言數組
    - (instancetype)initWithObjects:(const ObjectType _Nonnull [_Nullable])objects count:(NSUInteger)cnt NS_DESIGNATED_INITIALIZER;
    + (instancetype)arrayWithObjects:(const ObjectType _Nonnull [_Nonnull])objects count:(NSUInteger)cnt;

    // 通用
    - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;

    // 可變數組 ----
    - (instancetype)initWithCapacity:(NSUInteger)numItems NS_DESIGNATED_INITIALIZER;
    + (instancetype)arrayWithCapacity:(NSUInteger)numItems;
  • 例子
    // 單個元素
    NSArray *array = [NSArray arrayWithObject:@1];
    NSLog(@"%@", array);
    // 輸出:
    (
        1
    )

    // 多個元素
    NSArray *array = [NSArray arrayWithObjects:@1, @2, @3, @4, nil];
    NSLog(@"%@", array);
    // 輸出:
    (
        1,
        2,
        3,
        4
    )

    // 通過其他數組
    NSArray *arr = @[@1, @2, @3, @4];
    NSArray *array = [NSArray arrayWithArray:arr];
    NSLog(@"%@", array);
    // 輸出:
    (
        1,
        2,
        3,
        4
    )

    // 通過 文件 / url 
     NSArray *arrayFile = @[@1, @2, @3, @4];
    [arrayFile hy_writeToFileWithPath:HYAPPSandboxPathDocuments fileName:@"arrayFile.plist"];

    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *file = [filePath stringByAppendingPathComponent:@"arrayFile.plist"];
    NSArray *array = [[NSArray alloc] initWithContentsOfFile:file];
    NSLog(@"%@", array);

    NSError *error = nil;
    NSArray *array2 = [[NSArray alloc] initWithContentsOfURL:[NSURL fileURLWithPath:file] error:&error];
    if (!error) {
        NSLog(@"成功");
        NSLog(@"%@", array2);
    } else {
        NSLog(@"失敗");
        NSLog(@"%@", error);
    }
    // 輸出
    (
        1,
        2,
        3,
        4
    )
    成功
    (
        1,
        2,
        3,
        4
    )

    // 通過 c 語言數組
    NSString *strings[3];
    strings[0] = @"First";
    strings[1] = @"Second";
    strings[2] = @"Third";

    NSArray *stringsArray = [NSArray arrayWithObjects:strings count:2];
    NSLog(@"%@", stringsArray);
    // 輸出:
    (
        First,
        Second
    )
  • 小結
    • 通過 單個元素多個元素其他數組NSArray文件fileurlc 語言數組 構建數組

Java Array

  • 方法
    // 構造一個初始容量爲 10 的空列表
    public ArrayList()
    // 構造一個具有指定初始容量(initialCapacity)的空列表
    public ArrayList(int initialCapacity)
    // 構造一個包含指定 collection 的元素的列表,這些元素是按照該 collection 的迭代器返回它們的順序排列的。
    public ArrayList(Collection<? extends E> c)
  • 例子
    // 初始化
    ArrayList arrayList = new ArrayList();

    // 通過其他集合初始化
    ArrayList otherList = new ArrayList();
    otherList.add(1);
    otherList.add(2);

    ArrayList arrayList = new ArrayList(otherList);
    Log.e("數組", arrayList.toString());
    Log.e("數組", String.valueOf(arrayList.size()));
    // 輸出:
    E/數組: [1, 2]
    E/數組: 2
  • 小結

      • -

JS Array.from Array.of

  • 方法
    Array.from()
    Array.of(element0[, element1[, ...[, elementN]]])
  • 例子
    var array = Array.from('hello')
    console.log(array)
    // 輸出:
    ["h", "e", "l", "l", "o"]

    // 我是分割線 ------
    var array = Array.of(1, 2, "9")
    console.log(array)
    // 輸出:
    [1, 2, "9"]
  • 小結
    • Array.from() ,當傳入參數爲字符串時,可以作爲字符串分割數據的方法
    • -

小結

  • 相同點

      -
  • 不同點

二、長度 count size length

OC count

  • 方法
    @property (readonly) NSUInteger count;
  • 例子
    NSArray *array;
    NSLog(@"%@ : %ld", array, array.count);
    array = [NSArray array];
    NSLog(@"%@ : %ld", array, array.count);
    array = @[@"hello"];
    NSLog(@"%@ : %ld", array, array.count);

    // 輸出:
    (null) : 0
    (
    ) : 0
    (
        hello
    ) : 1
  • 小結
    • 數組爲空 nil ,沒有元素時,長度爲0

Java size

  • 方法
    public int size()
  • 例子
    ArrayList arrayList = new ArrayList();
    Log.e("數組", String.valueOf(arrayList.size()));
    arrayList.add(1);
    arrayList.add(2);
    Log.e("數組", String.valueOf(arrayList.size()));
    // 輸出:
    E/數組: 0
    E/數組: 2
  • 小結

      • -

JS length

  • 方法
    length
  • 例子
    var array = [1, 2, 3, 4, 5, 6];
    console.log(array.length)
    // 輸出:
    6
  • 小結

      • -

小結

  • 相同點

      -
  • 不同點

    - occountJavasizeJSlength

三、獲取 AtIndex get array[]

OC AtIndexfirstObject , lastObject

  • 方法
    // 快捷方式
    array[]

    // 獲取 index 位置處的元素,index 超過數組範圍會crash
    - (ObjectType)objectAtIndex:(NSUInteger)index;

    // 獲取第一個元素
    @property (nullable, nonatomic, readonly) ObjectType firstObject API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

    // 獲取最後一個元素
    @property (nullable, nonatomic, readonly) ObjectType lastObject;

    // 獲取多個元素
    - (NSArray<ObjectType> *)objectsAtIndexes:(NSIndexSet *)indexes;
  • 例子
    NSArray *array = @[@1, @2, @3, @4];
    NSLog(@"%@", [array objectAtIndex:0]);
    NSLog(@"%@", array[0]);
    NSLog(@"%@", [array firstObject]);
    NSLog(@"%@", [array lastObject]);

    // 輸出: (當傳入參數爲 -1 ,10 時 會crash)
    1
    1
    1
    4
  • 小結
    • 從數組 array 中獲取下標爲 index 的快捷方式 array[index] ,這種方式等價於 [array objectAtIndex:index]
    • 數組的下標從 0 開始,範圍爲 0length - 1,超過範圍會crash

Java get

  • 方法
    /**
     * 獲取 index 位置處的元素, index 超過 數組範圍 [0, size - 1] 會crash,即 index < 0 || index >= size()
     */
    public E get(int index)
  • 例子
    ArrayList arrayList = new ArrayList();
    arrayList.add(1);
    arrayList.add(2);
    Log.e("數組", String.valueOf(arrayList.get(0)));
    // 輸出:
    E/數組: 1

    // 分割線 -------

    int[] numbers = new int[3];
    numbers[0] = 1;
    numbers[1] = 2;
    Log.e("數組", String.valueOf(numbers[1]));
  • 小結
    • 數組的下標從 0 開始,範圍爲 0size - 1,超過範圍會crash
    • -

JS filter find findIndex

  • 方法
    // 快捷方式
    array[]

    /**
     * 方法創建一個新數組, 其包含通過所提供函數實現的測試的所有元素。
     * callback : 用來測試數組的每個元素的函數。調用時使用參數 (element, index, array)。返回true表示保留該元素(通過測試),false則不保留。
     * thisArg : 可選。執行 callback 時的用於 this 的值。
     * 返回值 : 一個新的通過測試的元素的集合的數組
     */
    var new_array = arr.filter(callback[, thisArg])

    /**
     * 方法返回數組中滿足提供的測試函數的第一個元素的值。否則返回 undefined。
     * callback :在數組每一項上執行的函數。調用時使用參數 (element, index, array)。
     * thisArg :可選,指定 callback 的 this 參數。
     * 返回值 : 當某個元素通過 callback 的測試時,返回數組中的一個值,否則返回 undefined。
     */
     arr.find(callback[, thisArg])

    /**
     * 方法返回數組中滿足提供的測試函數的第一個元素的索引。否則返回-1
     * callback :在數組每一項上執行的函數。調用時使用參數 (element, index, array)。
     * thisArg :可選,指定 callback 的 this 參數。
     * 返回值 : 當某個元素通過 callback 的測試時,返回數組中的一個值的索引 index ,否則返回 -1。
     */
     arr.findIndex(callback[, thisArg])
  • 例子
    var array = [1, 5, 15, 20, 30, 100, 200]
    console.log(array[1]) // 5
    console.log(array[-1]) // undefined
    console.log(array[100]) // undefined

    // 我是分割線 -------

    var array = [1, 5, 15, 20, 30, 100, 200]
    var result = array.filter(isBigEnough)
    console.log(result)

    function isBigEnough(element, index, array) {
        return element >= 10;
    }
    // 輸出:
    [15, 20, 30, 100, 200]

    // 我是分割線 -------

    var array = [1, 5, 15, 20, 30, 100, 200]
    var result = array.find(isBigEnough)
    console.log(result)
    // 輸出:
    15

    // 我是分割線 -------

    var array = [1, 5, 15, 20, 30, 100, 200]
    var result = array.findIndex(isBigEnough)
    console.log(result)
    // 輸出:
    2
  • 小結
    • filter 是查找符合條件的 所有 元素find 是查找符合條件的 第一個 元素findIndex 是查找符合條件的 第一個 元素的 索引
    • 索引位置 index 的下標從 0 開始,範圍爲 0length - 1,超過範圍獲取到的是 undefined

小結

  • 相同點

    - 如果數組的元素數目爲 count , 則索引位置/下標範圍爲 [0, count - 1]

  • 不同點

    - ocjava 索引位置超過範圍會 crash, js 不會報錯,但是獲取到的是 undefined

四、增加 add insert addAll concat push unshift

OC addinsert

  • 方法
    // 在 “末尾” 添加元素 ,“原來數組”不發生變化,返回一個新的數組
    - (NSArray<ObjectType> *)arrayByAddingObject:(ObjectType)anObject;

    // 在 “末尾” 添加其他數組
    - (NSArray<ObjectType> *)arrayByAddingObjectsFromArray:(NSArray<ObjectType> *)otherArray;

    // 可變數組 ---------
    // 在 末尾 添加元素
    - (void)addObject:(ObjectType)anObject;

    // 在 index 位置處 添加元素
    - (void)insertObject:(ObjectType)anObject atIndex:(NSUInteger)index;

    // 在 “末尾” 添加其他數組
    - (void)addObjectsFromArray:(NSArray<ObjectType> *)otherArray;

    // 把 objects 中的 集合索引 indexes 中的元素 依次取出,然後插入到 "源數組" 相應的 集合索引 indexes 中的位置處
    - (void)insertObjects:(NSArray<ObjectType> *)objects atIndexes:(NSIndexSet *)indexes;
  • 例子
    // 添加元素
    NSArray *array = @[@1, @2];
    NSArray *result = [array arrayByAddingObject:@4];
    NSLog(@"%@", result);
    // 輸出:
    (
        1,
        2,
        4
    )

    // 添加其他數組
    NSArray *otherArray = @[@10, @11];
    NSArray *array = @[@1, @2];
    NSArray *result = [array arrayByAddingObjectsFromArray:otherArray];
    NSLog(@"%@", result);
    // 輸出:
    (
        1,
        2,
        10,
        11
    )

    // 可變數組
    // 添加單個元素
    NSMutableArray *array = [NSMutableArray array];
    [array addObject:@1];
    NSLog(@"%@", array);
    // index 超過範圍(-1 或 10)會 crash
    [array insertObject:@2 atIndex:0];
    NSLog(@"%@", array);

    // 輸出:
    (
        1
    )
    (
        2,
        1
    )

    // 添加數組
    NSArray *otherArray = @[@10, @11];
    NSMutableArray *array = [NSMutableArray array];
    [array addObjectsFromArray:otherArray];
    NSLog(@"%@", array);
    // 輸出:
    (
        10,
        11
    )

    // 插入到特定位置
    NSArray *otherArray = @[@10, @11];
    NSMutableIndexSet *set = [NSMutableIndexSet indexSet];
    [set addIndex:0];
    [set addIndex:3];
    NSMutableArray *array = [NSMutableArray arrayWithObjects:@1, @2, @3, @4, @5, nil];
    [array insertObjects:otherArray atIndexes:set];
    NSLog(@"%@", array);
    // 輸出:
    (
        10,
        1,
        2,
        11,
        3,
        4,
        5
    )
  • 小結
    • NSArray “原來數組”不發生變化,返回新數組
    • NSMutableArray “原來數組”發生變化
    • 添加 nilNULL 元素 crash
    • 添加 @[][NSNull null] 元素 不會 crash
    • index 超過範圍會 crash

Java add addAll

  • 方法
    // 將元素e添加到此列表的尾部。
    public boolean add(E e)

    // 將元素element插入此列表中的指定位置index處。索引超過範圍會crash
    public void add(int index, E element)

    // 將該 collection 中的所有元素添加到此列表的尾部, 如果指定的 collection 爲 null 會 crash
    public boolean addAll(Collection<? extends E> c)

    // 將該 collection 中的所有元素添加到此列表中的指定位置index處, 如果指定的 collection 爲 null 會 crash, 索引超過範圍會crash
    public boolean addAll(int index, Collection<? extends E> c)
  • 例子
    ArrayList otherArray = new ArrayList();
    otherArray.add(1);
    otherArray.add(2);

    ArrayList arrayList = new ArrayList();
    arrayList.add(100);
    Log.e("數組", String.valueOf(arrayList));
    arrayList.add(0, 150);
    Log.e("數組", String.valueOf(arrayList));
    arrayList.addAll(otherArray);
    Log.e("數組", String.valueOf(arrayList));
    arrayList.addAll(1, otherArray);
    Log.e("數組", String.valueOf(arrayList));
    arrayList.add(null);
    Log.e("數組", String.valueOf(arrayList));
    // 輸出:
    E/數組: [100]
    E/數組: [150, 100]
    E/數組: [150, 100, 1, 2]
    E/數組: [150, 1, 2, 100, 1, 2]
    E/數組: [150, 1, 2, 100, 1, 2, null]
  • 小結
    • addAll 方法,添加的集合爲 nullcrash
    • add 方法,添加的元素爲 null 不會 crash
    • 索引位置超過範圍會 crash

JS concat push unshift

  • 方法
    // 添加 “元素” 或 “數組”,返回新數組,源數組和添加數組的值不改變
    var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])

    // 方法將一個或多個元素添加到數組的末尾,並返回新數組的長度。改變原數組的值
    arr.push(element1, ..., elementN)

    // 方法將一個或多個元素添加到數組的開頭,並返回新數組的長度。改變原數組的值
    arr.unshift(element1, ..., elementN)

    // 在某個 索引位置 處添加的方法 使用 splice 方法
  • 例子
    var array = []
    var array1 = [1, 2]
    var result = array.concat(100, array1, 200)
    console.log(result)
    console.log(array)
    console.log(array1)
    // 輸出:
    [100, 1, 2, 200]
    []
    [1, 2]

    // 分割線 ------

    var array = [1, 5]
    array.push(3, 10)
    console.log(array
    // 輸出:
    [1, 5, 3, 10]

    // 分割線 ------

    var array = [1, 5, 15]
    array.unshift(3000)
    console.log(array)
    // 輸出:
    [3000, 1, 5, 15]

    // 分割線 ------
    var array = [1, 2]
    array.push(null)
    array.push(undefined)
    console.log(array)
    // 輸出:
    [1, 2, null, undefined]
  • 小結
    • 數組添加 null undefined 不會報錯,並且存在於數組中
    • -

小結

  • 相同點

    - ocjava 索引超過範圍會 crashjs 不會

  • 不同點

    • oc 添加空值 nilNULL 元素 crash
    • java addAll 方法,添加的集合爲 nullcrash
    • java add 方法,添加的元素爲 null 不會 crash
    • js 添加空值 null undefined 不會報錯,並且存在於數組中

五、包含 contains includes

OC contains

  • 方法
    - (BOOL)containsObject:(ObjectType)anObject;
  • 例子
    NSArray *array = @[@1, @2, @3, @4, @5];
    BOOL result = [array containsObject:@0];
    if (result) {
        NSLog(@"包含");
    } else {
        NSLog(@"不包含");
    }

    BOOL result2 = [array containsObject:@2];
    if (result2) {
        NSLog(@"包含");
    } else {
        NSLog(@"不包含");
    }

    // 輸出:
    不包含
    包含
  • 小結

      • -

Java contains

  • 方法
    // 是否包含元素 e
    public boolean contains(Object o)
    // 是否包含集合 c 中的所有元素 
    public boolean containsAll(Collection<?> c)
  • 例子
    ArrayList arrayList = new ArrayList();
    arrayList.add(1);
    arrayList.add(2);
    arrayList.add(3);

    Log.e("數組", String.valueOf(arrayList.contains(1)));
    Log.e("數組", String.valueOf(arrayList.contains(100)));

    ArrayList otherArray = new ArrayList();
    otherArray.add(1);
    otherArray.add(2);
    Log.e("數組", String.valueOf(arrayList.containsAll(otherArray)));

    otherArray.add(100);
    Log.e("數組", String.valueOf(arrayList.containsAll(otherArray)));

    // 輸出:
    E/數組: true
    E/數組: false
    E/數組: true
    E/數組: false
  • 小結

      • -

JS includes

  • 方法
    /**
     * 方法用來判斷一個數組是否包含一個指定的值,如果包含則返回 true,否則返回false
     * searchElement :需要查找的元素
     * fromIndex :可選,從該索引處開始查找 searchElement。如果爲負值,則按升序從 array.length + fromIndex 的索引開始搜索。默認爲 0。
     * 返回值 :如果包含則返回 true,否則返回false
     * 1、如果fromIndex 大於等於數組長度 ,則返回 false 。該數組不會被搜索
     * 2、如果 fromIndex 爲負值,計算出的索引(array.length + fromIndex)將作爲開始搜索searchElement的位置。如果計算出的索引小於 0,則整個數組都會被搜索
     */
    arr.includes(searchElement, fromIndex)
  • 例子
    var array = [1, 5, 15, 20, 30, 100, 200]
    console.log(array.includes(1))
    console.log(array.includes(1, 2))
    console.log(array.includes(-200))
    console.log(array.includes(1, 20))
    console.log(array.includes(1, -100))
    // 輸出:
    true
    false
    false
    false
    true
  • 小結
    • 如果 fromIndex 大於等於數組長度 ,則返回 false 。該數組不會被搜索
    • 如果 fromIndex 爲負值,計算出的索引 (array.length + fromIndex) 將作爲開始搜索 searchElement 的位置。如果計算出的索引 小於0 ,則整個數組都會被搜索

小結

  • 相同點

      -
  • 不同點

六、查找 indexOf lastIndexOf

OC indexOf

  • 方法
    // 獲取 anObject 第一次出現的的索引位置,沒有獲取到返回 NSNotFound
    - (NSUInteger)indexOfObject:(ObjectType)anObject;
    - (NSUInteger)indexOfObject:(ObjectType)anObject inRange:(NSRange)range;
    - (NSUInteger)indexOfObjectIdenticalTo:(ObjectType)anObject;
    - (NSUInteger)indexOfObjectIdenticalTo:(ObjectType)anObject inRange:(NSRange)range;

    // todo
typedef NS_OPTIONS(NSUInteger, NSBinarySearchingOptions) {
    NSBinarySearchingFirstEqual = (1UL << 8),
    NSBinarySearchingLastEqual = (1UL << 9),
    NSBinarySearchingInsertionIndex = (1UL << 10),
};
    - (NSUInteger)indexOfObject:(ObjectType)obj inSortedRange:(NSRange)r options:(NSBinarySearchingOptions)opts usingComparator:(NSComparator NS_NOESCAPE)cmp API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0)); // binary search
  • 例子
    NSArray *array = @[@1, @2, @3, @4, @5, @2];
    NSLog(@"%ld", [array indexOfObject:@2]);
    NSLog(@"%ld", [array indexOfObject:@100]);
    NSLog(@"%ld", [array indexOfObject:@"2"]);
    NSLog(@"%ld", [array indexOfObject:@"100"]);
    NSLog(@"--------");
    NSLog(@"%ld", [array indexOfObjectIdenticalTo:@2]);
    NSLog(@"%ld", [array indexOfObjectIdenticalTo:@100]);
    NSLog(@"%ld", [array indexOfObjectIdenticalTo:@"2"]);
    NSLog(@"%ld", [array indexOfObjectIdenticalTo:@"100"]);

    // 輸出:
    1
    9223372036854775807
    9223372036854775807
    9223372036854775807
    --------
    1
    9223372036854775807
    9223372036854775807
    9223372036854775807
  • 小結

      • -

Java indexOf lastIndexOf

  • 方法
    // 此列表中第一次出現的指定元素的索引,如果列表不包含該元素,則返回 -1 
    public int indexOf(Object o)
    // 列表中最後出現的指定元素的索引;如果列表不包含此元素,則返回 -1 
    public int lastIndexOf(Object o)
  • 例子
    ArrayList arrayList = new ArrayList();
    arrayList.add(1);
    arrayList.add(2);
    arrayList.add(3);
    arrayList.add(2);

    Log.e("數組", String.valueOf(arrayList.indexOf(2)));
    Log.e("數組", String.valueOf(arrayList.indexOf(100)));
    Log.e("數組", String.valueOf(arrayList.lastIndexOf(2)));
    Log.e("數組", String.valueOf(arrayList.lastIndexOf(100)));

    // 輸出:
    E/數組: 1
    E/數組: -1
    E/數組: 3
    E/數組: -1
  • 小結

      • -

JS indexOf lastIndexOf

  • 方法
    /**
     * 方法返回在數組中可以找到一個給定元素的第一個索引,如果不存在,則返回-1
     * searchElement : 要查找的元素
     * fromIndex :可選的參數,默認爲0;開始查找的位置。
     * 1、如果 fromIndex 大於或等於數組長度,意味着不會在數組裏查找,返回-1
     * 2、如果 fromIndex 爲負數,則從 (array.length + fromIndex) 位置處開始查找,計算結果仍然爲負數,則從 0 位置處開始查找
     * 返回值 : 首個被找到的元素在數組中的索引位置; 若沒有找到則返回 -1
     */
    arr.indexOf(searchElement[, fromIndex = 0])

    // 從後往前查找,用法和 indexOf 相同
    arr.lastIndexOf(searchElement[, fromIndex = arr.length - 1])
  • 例子
    var array = [1, 5, 15, 20, 30, 100, 200]
    console.log(array.indexOf(1))
    console.log(array.indexOf(-100))
    console.log(array.indexOf(1, 3))
    console.log(array.indexOf(1, 100))
    console.log(array.indexOf(1, -1))
    console.log(array.indexOf(1, -100))
    // 輸出:
    0
    -1
    -1
    -1
    -1
    0

    // 分割線 ----

    var array = [1, 5, 15, 20, 30, 100, 200]
    console.log(array.lastIndexOf(1))
    console.log(array.lastIndexOf(-100))
    console.log(array.lastIndexOf(1, 3))
    console.log(array.lastIndexOf(1, 100))
    console.log(array.lastIndexOf(1, -1))
    console.log(array.lastIndexOf(1, -100))
    // 輸出:
    0
    -1
    0
    0
    0
    -1
  • 小結
    • indexOf從左往右 查找第一個元素的 索引位置
    • lastIndexOf從右往左 查找第一個元素的 索引位置

小結

  • 相同點

      -
  • 不同點

七、截取 subarray subList slice

OC subarray

  • 方法
    - (NSArray<ObjectType> *)subarrayWithRange:(NSRange)range;
    - (void)getObjects:(ObjectType _Nonnull __unsafe_unretained [_Nonnull])objects range:(NSRange)range NS_SWIFT_UNAVAILABLE("Use 'subarrayWithRange()' instead");
  • 例子
    NSArray *array = @[@1, @2, @3, @4];
    NSArray *result = [array subarrayWithRange:NSMakeRange(1, 2)];
    NSLog(@"%@", result);
    // 輸出:
    (
        2,
        3
    )
  • 小結
    • range 超過數組範圍時,會 crash

Java subList

  • 方法
    /**
     * 截取  fromIndex(包括 )和 toIndex(不包括)之間的內容
     * 1、fromIndex < 0 會 crash
     * 2、toIndex > 0 會 crash
     * 3、fromIndex < toIndex 會 crash
     * 4、fromIndex = toIndex 返回空數組[]
     * 5、fromIndex > size - 1 返回 空數組[]
     */
    public List<E> subList(int fromIndex, int toIndex)
  • 例子
    ArrayList arrayList = new ArrayList();
    arrayList.add(1);
    arrayList.add(2);
    arrayList.add(3);
    arrayList.add(2);

    Log.e("數組", String.valueOf(arrayList.subList(0, 2))); // [1, 2]
    Log.e("數組", String.valueOf(arrayList.subList(-1, 2))); // crash
    Log.e("數組", String.valueOf(arrayList.subList(0, 5))); // crash
    Log.e("數組", String.valueOf(arrayList.subList(4, 4))); // []
    Log.e("數組", String.valueOf(arrayList.subList(4, 2))); // crash
    Log.e("數組", String.valueOf(arrayList.subList(2, 2))); // [[]
  • 小結

      • -

JS slice

  • 方法
    /**
     * 方法返回一個從開始到結束(不包括結束)選擇的數組的一部分淺拷貝到一個新數組對象。原始數組不會被修改。
     * begin : 可選的,默認爲0;如果爲負數,則從 (array.length + begin) 開始截取
     * end :可選的,默認是截取到數組結尾處;如果爲負數,則截取到 (array.length + begin) 位置處
     * 1、如果 end 被省略,則slice 會一直提取到原數組末尾
     * 2、如果 end 大於數組長度,slice 也會一直提取到原數組末尾。
     * 3、如果 begin 大於 end,slice 返回空數組。
     */
    // 截取範圍 [0, end] ,即“整個數組”
    arr.slice();
    // 截取範圍 [begin, end] ,從 begin 位置處截取(包含該位置),一直到數組末尾
    arr.slice(begin);
    // 截取範圍 [begin, end) ,包含 begin 位置元素,不包含 end 位置元素
    arr.slice(begin, end);
  • 例子
    var array = [1, 5, 15, 20, 30, 100, 200]
    console.log(array.slice()) // [1, 5, 15, 20, 30, 100, 200]
    console.log(array.slice(2)) // [15, 20, 30, 100, 200]
    console.log(array.slice(2, 5)) // [15, 20, 30]
    console.log(array.slice(2, 100)) // [15, 20, 30, 100, 200]
    console.log(array.slice(5, 2)) // []
    console.log(array.slice(-5)) // [15, 20, 30, 100, 200]
    console.log(array.slice(-5, -3)) // [15, 20]
  • 小結
    • 類似字符串的 slice 方法
    • -

小結

  • 相同點

    - ocjava 超過範圍會報錯

  • 不同點

八、替換 replace set splice fill

OC replace

  • 方法
    // 可變數組 ----
    // 替換 index 位置處的元素 爲 anObject
    - (void)replaceObjectAtIndex:(NSUInteger)index withObject:(ObjectType)anObject;
    // “源數組” range 範圍的元素 用 otherArray 數組的 otherRange 範圍內的元素替換
    - (void)replaceObjectsInRange:(NSRange)range withObjectsFromArray:(NSArray<ObjectType> *)otherArray range:(NSRange)otherRange;
    // “源數組” range 範圍的元素 用 otherArray 數組替換
    - (void)replaceObjectsInRange:(NSRange)range withObjectsFromArray:(NSArray<ObjectType> *)otherArray;
    // “源數組” indexes 位置集合處的元素依次用 objects 數組中相應位置處的元素替換,indexes 的長度 和 objects 長度不一致的話會crash
    - (void)replaceObjectsAtIndexes:(NSIndexSet *)indexes withObjects:(NSArray<ObjectType> *)objects;
  • 例子
    NSMutableArray *array = [NSMutableArray arrayWithObjects:@1, @2, @3, @4, @5, @6, nil];
    [array replaceObjectAtIndex:2 withObject:@100];
    [array replaceObjectAtIndex:2 withObject:@"string"];
    NSLog(@"%@", array);
    // 輸出:
    (
        1,
        2,
        string,
        4,
        5,
        6
    )

     NSMutableArray *array = [NSMutableArray arrayWithObjects:@1, @2, @3, @4, @5, @6, @7, @8, @9, nil];
    NSArray *otherArray = @[@20, @21, @22];
    [array replaceObjectsInRange:NSMakeRange(1, 2) withObjectsFromArray:otherArray];
    NSLog(@"%@", array);
    [array replaceObjectsInRange:NSMakeRange(7, 3) withObjectsFromArray:otherArray range:NSMakeRange(1, 2)];
    NSLog(@"%@", array);

    NSMutableIndexSet *set = [NSMutableIndexSet indexSet];
    [set addIndex:0];
    [set addIndex:1];
    [set addIndex:5];
    [array replaceObjectsAtIndexes:set withObjects:otherArray];
    NSLog(@"%@", array);

    // 輸出:
    (
        1,
        20,
        21,
        22,
        4,
        5,
        6,
        7,
        8,
        9
    )
    (
        1,
        20,
        21,
        22,
        4,
        5,
        6,
        21,
        22
    )
    (
        20,
        21,
        21,
        22,
        4,
        22,
        6,
        21,
        22
    )
  • 小結
    • indexrange 超過範圍會crash
    • replaceObjectsAtIndexes 方法如果 indexes 的長度 和 objects 長度不一致的話會crash : *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSMutableArray replaceObjectsAtIndexes:withObjects:]: count of array (3) differs from count of index set (2)'

Java set

  • 方法
    // 用指定元素 element 替換列表中指定位置 index 的元素
    public E set(int index, E element)
  • 例子
    ArrayList arrayList = new ArrayList();
    arrayList.add(1);
    arrayList.add(2);
    arrayList.add(3);
    arrayList.add(2);

    arrayList.set(1, 100);
    Log.e("數組", String.valueOf(arrayList)); // [1, 100, 3, 2]
    arrayList.set(1, null);
    Log.e("數組", String.valueOf(arrayList)); // E/數組: [1, null, 3, 2]
    arrayList.set(-1, null); // crash
    Log.e("數組", String.valueOf(arrayList)); 
  • 小結
    • crash 情況:
      • UnsupportedOperationException - 如果列表不支持 set 操作
      • ClassCastException - 如果指定元素的類不允許它添加到此列表
      • NullPointerException - 如果指定的元素爲 null,並且此列表不允許 null 元素
      • IllegalArgumentException - 如果指定元素的某些屬性不允許它添加到此列表
      • IndexOutOfBoundsException - 如果索引超出範圍( index < 0 || index >= size())
    • -

JS fill splice

  • 方法
    /**
     * 用一個固定值填充一個數組中從起始索引到終止索引內的全部元素
     * value : 用來填充數組元素的值
     * start :可選的,起始索引,默認值爲0
     * end : 可選的,終止索引,默認值爲 this.length
     * 填充範圍是一個左閉右開區間,[start, end),包含 start ,不包含 end 
     * 如果 start 是個負數, 則開始索引會被自動計算成爲 length+start
     * 如果 end 是個負數, 則結束索引會被自動計算成爲 length+end
     */
    arr.fill(value[, start[, end]])

    /**
     * 方法通過刪除現有元素和/或添加新元素來更改一個數組的內容。
     * start :指定修改的開始位置(從0計數
     *      1、如果超出了數組的長度,則從數組末尾開始添加內容
     *      2、如果是負值,則表示從 (array.length + start) 開始,
     *      3、若只使用start參數而不使用deleteCount、item,如:    array.splice(start) ,表示刪除[start,end]的元素。
     * deleteCount : 可選的,整數,表示要移除的數組元素的個數。
     * item1, item2, ... :可選的,要添加進數組的元素
     */
    array.splice(start)
    array.splice(start, deleteCount) 
    array.splice(start, deleteCount, item1, item2, ...)
  • 例子
    var array = [1, 2, 3, 4]
    array.fill(100) // [100, 100, 100, 100]
    array.fill(100, 1, 3) // [1, 100, 100, 4]
    array.fill(100, 1, 1) // [1, 2, 3, 4]
    array.fill(100, 1, 0) // [1, 2, 3, 4]
    array.fill(100, -2, -1) // [1, 2, 100, 4]

    // 分割線 ----
        var array = [1, 5, 15, 20, 30, 100, 200]
    console.log(array.splice(4)) // [1, 5, 15, 20]
    console.log(array) // [1, 5, 15, 20]
    // -------
    console.log(array.splice(-4)) // [20, 30, 100, 200]
    console.log(array) // [1, 5, 15]
    // -------
    console.log(array.splice(100)) // []
    console.log(array) // [1, 5, 15, 20, 30, 100, 200]

    var array = [1, 5, 15, 20, 30, 100, 200]
    console.log(array.splice(4, 2)) // [30, 100]
    console.log(array) // [1, 5, 15, 20, 200]
    // -------
    console.log(array.splice(-4, 2)) // [20, 30]
    console.log(array) // [1, 5, 15, 100, 200]
    // -------
    console.log(array.splice(100, 2)) // []
    console.log(array) // [1, 5, 15, 20, 30, 100, 200]

    var array = [1, 5, 15, 20, 30, 100, 200]
    console.log(array.splice(4, 2, "add")) // [30, 100]
    console.log(array) // [1, 5, 15, 20, "add", 200]
    // -------
    console.log(array.splice(-4, 2, "add")) // [20, 30]
    console.log(array) // [1, 5, 15, "add", 100, 200]
    // -------
    console.log(array.splice(100, 2, "add")) // []
    console.log(array) // [1, 5, 15, 20, 30, 100, 200, "add"]
  • 小結
    • fill 方法當 start > end 的時候纔會進行填充
    • splice 方法根據傳入的參數不同表現出不同的狀態
      • array.splice(start)start 位置處開始(包含start位置),一直刪除到數組末尾
      • array.splice(start, deleteCount)start 位置處開始(包含start位置),刪除 deleteCount 個元素
      • array.splice(start, deleteCount, item1, item2, ...)start 位置處開始(包含start位置),刪除 deleteCount 個元素,然後再在 start 位置處插入元素 item1, item2, ...

小結

  • 相同點

      -
  • 不同點

九、刪除 remove removeAll clear pop shift

OC remove

  • 方法
    // 可變數組 -----
    // 刪除最後一個元素
    - (void)removeLastObject;
    // 刪除 index 位置處的元素
    - (void)removeObjectAtIndex:(NSUInteger)index;
    // 刪除所有的元素
    - (void)removeAllObjects;
    // 刪除“所有”的 anObject 元素
    - (void)removeObject:(ObjectType)anObject;
    // 刪除 range 範圍內的“所有”的 anObject 元素
    - (void)removeObject:(ObjectType)anObject inRange:(NSRange)range;
    - (void)removeObjectIdenticalTo:(ObjectType)anObject inRange:(NSRange)range;
    - (void)removeObjectIdenticalTo:(ObjectType)anObject;
    - (void)removeObjectsFromIndices:(NSUInteger *)indices numIndices:(NSUInteger)cnt API_DEPRECATED("Not supported", macos(10.0,10.6), ios(2.0,4.0), watchos(2.0,2.0), tvos(9.0,9.0));
    // 刪除 otherArray 數組內包含的元素
    - (void)removeObjectsInArray:(NSArray<ObjectType> *)otherArray;
    // 刪除 range 範圍內的元素
    - (void)removeObjectsInRange:(NSRange)range;
    - (void)removeObjectsAtIndexes:(NSIndexSet *)indexes;
  • 例子
    NSMutableArray *array = [NSMutableArray arrayWithObjects:@1, @2, @3, @4, @5, @6, @7, @8, @9, nil];
    [array removeLastObject];
    NSLog(@"%@", array);
    NSLog(@"------");

    [array removeObjectAtIndex:1];
    NSLog(@"%@", array);
    NSLog(@"------");

    [array removeAllObjects];
    NSLog(@"%@", array);
    NSLog(@"------");

    // 輸出:
    (
        1,
        2,
        3,
        4,
        5,
        6,
        7,
        8
    )
    ------
    (
        1,
        3,
        4,
        5,
        6,
        7,
        8
    )
    ------
    (
    )
    ------

    // 我是分割線 ------------
    NSMutableArray *array = [NSMutableArray arrayWithObjects:@1, @2, @3, @4, @5, @6, @7, @8, @9, @1, @2, @3, @4, @5, nil];
    [array removeObject:@2];
    NSLog(@"%@", array);
    // 輸出:
    (
        1,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        1,
        3,
        4,
        5
    )

     NSMutableArray *array = [NSMutableArray arrayWithObjects:@1, @2, @3, @4, @5, @6, @7, @8, @9, @1, @2, @3, @4, @5, nil];
    [array removeObject:@2 inRange:NSMakeRange(0, 5)];
    NSLog(@"%@", array);
    // 輸出:
    (
        1,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        1,
        2,
        3,
        4,
        5
    )

    NSMutableArray *array = [NSMutableArray arrayWithObjects:@1, @2, @3, @4, @5, @6, @7, @8, @9, @1, @2, @3, @4, @5, nil];
    [array removeObjectsInArray:@[@1, @5]];
    NSLog(@"%@", array);
    // 輸出:
    (
        2,
        3,
        4,
        6,
        7,
        8,
        9,
        2,
        3,
        4
    )

     NSMutableArray *array = [NSMutableArray arrayWithObjects:@1, @2, @3, @4, @5, @6, @7, @8, @9, @1, @2, @3, @4, @5, nil];
    [array removeObjectsInRange:NSMakeRange(0, 5)];
    NSLog(@"%@", array);
    // 輸出:
    (
        6,
        7,
        8,
        9,
        1,
        2,
        3,
        4,
        5
    )

     NSMutableArray *array = [NSMutableArray arrayWithObjects:@1, @2, @3, @4, @5, @6, @7, @8, @9, @1, @2, @3, @4, @5, nil];
    NSMutableIndexSet *set = [NSMutableIndexSet indexSet];
    [set addIndex:0];
    [set addIndex:1];
    [set addIndex:5];
    [array removeObjectsAtIndexes:set];
    NSLog(@"%@", array);
    // 輸出:
    (
        3,
        4,
        5,
        7,
        8,
        9,
        1,
        2,
        3,
        4,
        5
    )
  • 小結

      • -

Java remove removeAll clear

  • 方法
    // 刪除 index 位置處的元素,index 超過範圍會 crash 
    public E remove(int index)

    // 移除此列表中"首次"出現的指定元素(如果存在)。如果列表不包含此元素,則列表不做改動。
    public boolean remove(Object o)

    // 刪除 所有在集合 c 中的元素
    public boolean removeAll(Collection<?> c)
    // 移除所有的元素
    public void clear()
  • 例子
    ArrayList arrayList = new ArrayList();
    arrayList.add(1);
    arrayList.add(2);
    arrayList.add(3);
    arrayList.add(2);

    arrayList.remove(1);
    Log.e("數組", String.valueOf(arrayList));
    // 輸出:
    E/數組: [1, 3, 2]

    // 分割線 ------

    ArrayList arrayList = new ArrayList();
    arrayList.add("a");
    arrayList.add("b");
    arrayList.add("c");
    arrayList.add("b");

    arrayList.remove("b");
    Log.e("數組", String.valueOf(arrayList));
    // 輸出:
    E/數組: [a, c, b]

    // 分割線 ------

    ArrayList arrayList = new ArrayList();
    arrayList.add("a");
    arrayList.add("b");
    arrayList.add("c");
    arrayList.add("b");

    arrayList.clear();
    Log.e("數組", String.valueOf(arrayList));
    // 輸出:
    E/數組: []

    // 分割線 ------

    ArrayList otherList = new ArrayList();
    otherList.add("a");
    otherList.add("b");
    otherList.add("x");

    ArrayList arrayList = new ArrayList();
    arrayList.add("a");
    arrayList.add("b");
    arrayList.add("c");
    arrayList.add("b");

    arrayList.removeAll(otherList);
    Log.e("數組", String.valueOf(arrayList));
    // 輸出:
    E/數組: [c]
  • 小結

      • -

JS pop shift

  • 方法
    // 方法從數組中刪除最後一個元素,並返回該元素的值。此方法更改數組的長度
    arr.pop()

    // 方法從數組中刪除第一個元素,並返回該元素的值。此方法更改數組的長度。
    arr.shift()

    // 刪除 index 位置處元素用 splice 方法
  • 例子
    var array = [1, 5, 15, 20, 30, 100, 200]
    array.pop()
    console.log(array)
    // 輸出:
    [1, 5, 15, 20, 30, 100]

    // 分割線 ---------

    var array = [1, 5, 15, 20, 30, 100, 200]
    array.shift()
    console.log(array)
    // 輸出:
    [5, 15, 20, 30, 100, 200]
  • 小結

      • -

小結

  • 相同點

    - oc 方法 - (void)removeObjectsInArray:(NSArray<ObjectType> *)otherArray; 類似 java 方法 public boolean removeAll(Collection<?> c)

  • 不同點

    • oc 中移除某個元素方法 - (void)removeObject:(ObjectType)anObject; 是移除所有的 anObject 元素;
    • javapublic boolean remove(Object o) 是移除第一個出現的元素,移除所有的 使用方法 public boolean removeAll(Collection<?> c)

十、排序 sort

OC sort

  • 方法
    @property (readonly, copy) NSData *sortedArrayHint;

    // 使用函數排序
    - (NSArray<ObjectType> *)sortedArrayUsingFunction:(NSInteger (NS_NOESCAPE *)(ObjectType, ObjectType, void * _Nullable))comparator context:(nullable void *)context;
    - (NSArray<ObjectType> *)sortedArrayUsingFunction:(NSInteger (NS_NOESCAPE *)(ObjectType, ObjectType, void * _Nullable))comparator context:(nullable void *)context hint:(nullable NSData *)hint;

    // 使用SEL排序
    - (NSArray<ObjectType> *)sortedArrayUsingSelector:(SEL)comparator;
    - (NSArray<ObjectType> *)sortedArrayUsingComparator:(NSComparator NS_NOESCAPE)cmptr API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
    - (NSArray<ObjectType> *)sortedArrayWithOptions:(NSSortOptions)opts usingComparator:(NSComparator NS_NOESCAPE)cmptr API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
    // 可變數組 ----
    - (void)sortUsingFunction:(NSInteger (NS_NOESCAPE *)(ObjectType,  ObjectType, void * _Nullable))compare context:(nullable void *)context;
    - (void)sortUsingSelector:(SEL)comparator;
    - (void)sortUsingComparator:(NSComparator NS_NOESCAPE)cmptr API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
    - (void)sortWithOptions:(NSSortOptions)opts usingComparator:(NSComparator NS_NOESCAPE)cmptr API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

    // 多個條件的排序
    - (NSArray<ObjectType> *)sortedArrayUsingDescriptors:(NSArray<NSSortDescriptor *> *)sortDescriptors;    // returns a new array by sorting the objects of the receiver
  • 例子
    NSMutableArray *array = [NSMutableArray arrayWithObjects:@200, @20, @50, @30, @1, nil];
    [array sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2];
    }];
    NSLog(@"%@", array);
    // 輸出 :
     (
        1,
        20,
        30,
        50,
        200
    )
  • 小結

      • -

Java sort

  • 方法
    // 集合的排序
    Collections.sort
    public void sort(Comparator<? super E> c)
  • 例子
    ArrayList arrayList = new ArrayList();
    arrayList.add("x");
    arrayList.add("d");
    arrayList.add("b");
    arrayList.add("c");
    arrayList.add("a");
//        Collections.sort(arrayList, new Comparator() {
//            @Override
//            public int compare(Object o1, Object o2) {
//                return o1.toString().compareTo(o2.toString());
//            }
//        });
//
//        Log.e("數組", String.valueOf(arrayList));

    arrayList.sort(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            return o1.toString().compareTo(o2.toString());
        }
    });
    Log.e("數組", String.valueOf(arrayList));

    // 輸出:上面兩種排序方法結果是一樣的
    E/數組: [a, b, c, d, x]
  • 小結

      • -

JS sort

  • 方法
    // 根據字符串Unicode碼點排序
    arr.sort() 
  /**
   * 根據自定的函數 compareFunction 進行排序;
   * 1、如果 compareFunction(a, b) 小於 0 ,那麼 a 會被排列到 b 之前
   * 2、如果 compareFunction(a, b) 等於 0 , a 和 b 的相對位置不變
   * 3、如果 compareFunction(a, b) 大於 0 , b 會被排列到 a 之前
   */
    arr.sort(compareFunction)
  • 例子
    var fruit = ['cherries', 'apples', 'bananas'];
    fruit.sort(); 
    console.log(fruit)
    // 輸出:
    ["apples", "bananas", "cherries"]

    // 分割線 ----
    var numbers = [4, 2, 5, 1, 3];
    numbers.sort(function (a, b) {
      return a - b;
    });
    console.log(numbers)
    // 輸出:
    [1, 2, 3, 4, 5]
  • 小結

      • -

小結

  • 相同點

      -
  • 不同點

十一、比較/相等 Equal ==

OC Equal

  • 方法
    - (BOOL)isEqualToArray:(NSArray<ObjectType> *)otherArray;
  • 例子
    NSArray *array = @[@1, @2, @3, @4];
    NSArray *otherArray = @[@1, @2, @3, @4];
    NSArray *otherArray2 = @[@"1", @"2", @"3", @"4"];
    NSArray *otherArray3 = @[@1, @2];

    if ([array isEqualToArray:otherArray]) {
        NSLog(@"相等");
    } else {
        NSLog(@"不相等");
    }

    if ([array isEqualToArray:otherArray2]) {
        NSLog(@"相等");
    } else {
        NSLog(@"不相等");
    }

    if ([array isEqualToArray:otherArray3]) {
        NSLog(@"相等");
    } else {
        NSLog(@"不相等");
    }

    // 輸出:
    相等
    不相等
    不相等
  • 小結
    • 數組的長度相同,相同位置處的元素相同(類型和值),纔是相等的

Java equals

  • 方法
    // 將指定的對象與此列表進行相等性比較。當且僅當指定的對象也是一個列表,兩個列表具有相同的大小,而且兩個列表中所有相應的元素對都 相等 時,才返回 true。
    public boolean equals(Object o)
  • 例子
    ArrayList arrayList = new ArrayList();
    arrayList.add("x");
    arrayList.add("d");
    arrayList.add("b");
    arrayList.add("c");
    arrayList.add("a");

    ArrayList otherList = new ArrayList();
    otherList.add("a");
    otherList.add("b");
    otherList.add("x");

    ArrayList arrayList2 = new ArrayList();
    arrayList2.add("x");
    arrayList2.add("d");
    arrayList2.add("b");
    arrayList2.add("c");
    arrayList2.add("a");

    Log.e("數組", String.valueOf(arrayList.equals(otherList)));
    Log.e("數組", String.valueOf(arrayList.equals(arrayList2)));
    // 輸出:
    E/數組: false
    E/數組: true
  • 小結

      • -

JS ==

  • 方法
    ==
  • 例子
    var array = ['a', 'b', 'c']
    var other = ['z', 'x', 'y']
    console.log(array == other) // false
    console.log(array == array) // true
  • 小結

      • -

小結

  • 相同點

      -
  • 不同點

十二、連接 join

OC Joined

  • 方法
    // 數組中的元素 通過字符串 separator 連接
    - (NSString *)componentsJoinedByString:(NSString *)separator;
  • 例子
    NSArray *array = @[@1, @2, @3, @4, @5];
    NSString *result = [array componentsJoinedByString:@"+"];
    NSLog(@"%@", result);
    // 輸出:
    1+2+3+4+5
  • 小結
    • 這是數組“連接”成字符串,對應的字符串分割成數組方法爲:

      // 根據 指定的字符串 separator 進行分割
      <ul><li>(NSArray<NSString *> *)componentsSeparatedByString:(NSString *)separator;
      // 根據 指定的字符集合 separator 進行分割</li>
      <li>(NSArray<NSString *> *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));

Java 無直接方法

  • 方法
    沒有直接的方法,需要自己處理
    一、循環語句拼接字符串
  • 例子
    ArrayList arrayList = new ArrayList();
    arrayList.add("x");
    arrayList.add("d");
    arrayList.add("b");
    arrayList.add("c");
    arrayList.add("a");

    String separator = "+";
    StringBuffer sb = new StringBuffer("");
    for (int i = 0; i < arrayList.size(); i++) {
        Object ob = arrayList.get(i);
        sb.append(ob.toString());
        if (i != arrayList.size() - 1) {
            sb.append(separator);
        }
    }
    Log.e("數組", sb.toString());
    // 輸出:
    E/數組: x+d+b+c+a
  • 小結

      • -

JS join

  • 方法
    // 默認爲 ","
    str = arr.join()
    // 分隔符 === 空字符串 ""
    str = arr.join("")
    // 分隔符
    str = arr.join(separator)
  • 例子
    var array = [1, 5, 15, 20, 30, 100, 200]
    console.log(array.join())
    console.log(array.join(""))
    console.log(array.join("+"))
    // 輸出:
    1,5,15,20,30,100,200
    15152030100200
    1+5+15+20+30+100+200
  • 小結

      • -

小結

  • 相同點

      -
  • 不同點

十三、反轉 reverse

OC reverse

  • 方法
    - (NSEnumerator<ObjectType> *)reverseObjectEnumerator;
  • 例子
    NSArray *array = @[@1, @2, @3, @4, @5];
    NSArray *result = [[array reverseObjectEnumerator] allObjects];
    NSLog(@"%@", result);
    // 輸出:
    (
        5,
        4,
        3,
        2,
        1
    )
  • 小結

      • -

Java reverse

  • 方法 reverse
    // 集合的反轉方法
    Collections.reverse
  • 例子
    ArrayList arrayList = new ArrayList();
    arrayList.add("x");
    arrayList.add("d");
    arrayList.add("b");
    arrayList.add("c");
    arrayList.add("a");

    Collections.reverse(arrayList);
    Log.e("數組", String.valueOf(arrayList));
    // 輸出:
    E/數組: [a, c, b, d, x]
  • 小結

      • -

JS reverse

  • 方法
    arr.reverse()
  • 例子
    var array = [1, 2, 3, 4]
    var result = array.reverse()
    console.log(result)
    // 輸出:
    [4, 3, 2, 1]
  • 小結

      • -

小結

  • 相同點

      -
  • 不同點

十四、交換 exchange

OC exchange

  • 方法
    // 可變數組 ----
    - (void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2;
  • 例子
    NSMutableArray *array = [NSMutableArray arrayWithObjects:@1, @2, @3, @4, nil];
    [array exchangeObjectAtIndex:0 withObjectAtIndex:2];
    NSLog(@"%@", array);
    // 輸出:
    (
        3,
        2,
        1,
        4
    )
  • 小結

      • -

Java 無直接方法

  • 方法
    // 沒有直接方法,思路如下,和 js 類似
    1、取出 index 和 otherIndex 位置處的元素 indexElement ,otherIndexElement
    2、刪除 index 位置處的元素,插入 otherIndexElement  (也可以進行替換操作)
    3、刪除 otherIndex 位置處的元素,插入 indexElement (也可以進行替換操作)
  • 例子
    ArrayList arrayList = new ArrayList();
    arrayList.add("x");
    arrayList.add("d");
    arrayList.add("b");
    arrayList.add("c");
    arrayList.add("a");

    int index = 1;
    int otherIndex = 3;
    Object indexElement = arrayList.get(index);
    Object otherIndexElement = arrayList.get(otherIndex);

    arrayList.set(index, otherIndexElement);
    arrayList.set(otherIndex, indexElement);
    Log.e("數組", String.valueOf(arrayList));
    // 輸出 :
    E/數組: [x, c, b, d, a]
  • 小結

      • -

JS 無直接方法

  • 方法
    沒有直接的方法實現,思路如下
    1、取出 index 和 otherIndex 位置處的元素 indexElement ,otherIndexElement
    2、刪除 index 位置處的元素,插入 otherIndexElement
    3、刪除 otherIndex 位置處的元素,插入 indexElement
  • 例子
  var array = [1, 2, 3, 4, 5]
  var index = 1
  var otherIndex = 3
  var indexElement = array[index]
  var otherIndexElement = array[otherIndex]
  array.splice(index, 1, otherIndexElement)
  array.splice(otherIndex, 1, indexElement)
  console.log(array)
  // 輸出:
  [1, 4, 3, 2, 5]
  • 小結

      • -

小結

  • 相同點

      -
  • 不同點

十五、寫入/讀取 write init

OC write init

  • 方法
    // 寫入 ,11.0 之後可以使用
    - (BOOL)writeToURL:(NSURL *)url error:(NSError **)error API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0));
    // 寫入,後續會被廢棄
    - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile;
    - (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically;

    // 讀取,11.0 之後可以使用
    - (nullable NSArray<ObjectType> *)initWithContentsOfURL:(NSURL *)url error:(NSError **)error  API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0));
    + (nullable NSArray<ObjectType> *)arrayWithContentsOfURL:(NSURL *)url error:(NSError **)error API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0)) NS_SWIFT_UNAVAILABLE("Use initializer instead");
    // 讀取,後續會被廢棄掉
    + (nullable NSArray<ObjectType> *)arrayWithContentsOfFile:(NSString *)path;
    + (nullable NSArray<ObjectType> *)arrayWithContentsOfURL:(NSURL *)url;
    - (nullable NSArray<ObjectType> *)initWithContentsOfFile:(NSString *)path;
    - (nullable NSArray<ObjectType> *)initWithContentsOfURL:(NSURL *)url;
    ```

- 例子
// 寫入 ----
NSArray *array = @[@1, @2, @3, @4];
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *file = [filePath stringByAppendingPathComponent:@"array.plist"];
[array writeToFile:file atomically:YES];

NSError *error;
[array writeToURL:[NSURL fileURLWithPath:file] error:&error];
if (!error) {
    NSLog(@"寫入成功");
} else {
    NSLog(@"寫入失敗");
}
// 輸出:
寫入成功

// 讀取 : 參考初始化的 file 或 url 方法
```
  • 小結
    • 11.0 之後可以使用帶有 error 參數的方法,不帶 error 參數的方法後續會被廢棄掉

Java

  • 方法

  • 例子

  • 小結

JS

  • 方法

  • 例子

  • 小結

小結

  • 相同點

      -
  • 不同點

十六、遍歷 make Perform enumerate for循環語句 forEach for...of

OC makePerformenumerate, for循環語句

  • 方法
    // for..in 遍歷
     for (<#type *object#> in <#collection#>) {
            <#statements#>
     }
    // SEL 遍歷
    - (void)makeObjectsPerformSelector:(SEL)aSelector NS_SWIFT_UNAVAILABLE("Use enumerateObjectsUsingBlock: or a for loop instead");
    - (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(nullable id)argument NS_SWIFT_UNAVAILABLE("Use enumerateObjectsUsingBlock: or a for loop instead");

    // block 遍歷
    - (void)enumerateObjectsUsingBlock:(void (NS_NOESCAPE ^)(ObjectType obj, NSUInteger idx, BOOL *stop))block API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
    // block 遍歷,NSEnumerationConcurrent : 併發;NSEnumerationReverse : 反向;
    - (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (NS_NOESCAPE ^)(ObjectType obj, NSUInteger idx, BOOL *stop))block API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
    // block 遍歷,s 索引集合的元素
    - (void)enumerateObjectsAtIndexes:(NSIndexSet *)s options:(NSEnumerationOptions)opts usingBlock:(void (NS_NOESCAPE ^)(ObjectType obj, NSUInteger idx, BOOL *stop))block API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

    - (NSUInteger)indexOfObjectPassingTest:(BOOL (NS_NOESCAPE ^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
    - (NSUInteger)indexOfObjectWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (NS_NOESCAPE ^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
    - (NSUInteger)indexOfObjectAtIndexes:(NSIndexSet *)s options:(NSEnumerationOptions)opts passingTest:(BOOL (NS_NOESCAPE^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

    - (NSIndexSet *)indexesOfObjectsPassingTest:(BOOL (NS_NOESCAPE ^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
    - (NSIndexSet *)indexesOfObjectsWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (NS_NOESCAPE ^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
    - (NSIndexSet *)indexesOfObjectsAtIndexes:(NSIndexSet *)s options:(NSEnumerationOptions)opts passingTest:(BOOL (NS_NOESCAPE ^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
  • 例子
     NSArray *array = @[@1, @2, @3, @4, @5];
    for (NSNumber *ob in array) {
        NSLog(@"%@", ob);
    }
    // 輸出:
    1
    2
    3
    4
    5

    // 分割線 ---------

    NSArray *array = @[@1, @2, @3, @4];
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%ld : %@", idx, obj);
    }];
    NSLog(@"-----");
    [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%ld : %@", idx, obj);

    }];
    NSLog(@"-----");
    [array enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%ld : %@", idx, obj);

    }];
    NSLog(@"-----");
    NSMutableIndexSet *set = [NSMutableIndexSet indexSet];
    [set addIndex:0];
    [set addIndex:2];
    [set addIndex:3];
    [array enumerateObjectsAtIndexes:set options:0 usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%ld : %@", idx, obj);

    }];

    // 輸出:
    2018-02-27 13:11:41.886616+0800 HYFoundation[26729:24088389] 0 : 1
2018-02-27 13:11:41.886756+0800 HYFoundation[26729:24088389] 1 : 2
2018-02-27 13:11:41.886857+0800 HYFoundation[26729:24088389] 2 : 3
2018-02-27 13:11:41.886971+0800 HYFoundation[26729:24088389] 3 : 4
2018-02-27 13:11:41.887069+0800 HYFoundation[26729:24088389] -----
2018-02-27 13:11:41.887174+0800 HYFoundation[26729:24088389] 3 : 4
2018-02-27 13:11:41.887275+0800 HYFoundation[26729:24088389] 2 : 3
2018-02-27 13:11:41.887380+0800 HYFoundation[26729:24088389] 1 : 2
2018-02-27 13:11:41.887484+0800 HYFoundation[26729:24088389] 0 : 1
2018-02-27 13:11:41.887593+0800 HYFoundation[26729:24088389] -----
2018-02-27 13:11:41.887728+0800 HYFoundation[26729:24088389] 0 : 1
2018-02-27 13:11:41.887734+0800 HYFoundation[26729:24088493] 1 : 2
2018-02-27 13:11:41.887748+0800 HYFoundation[26729:24088492] 2 : 3
2018-02-27 13:11:41.887755+0800 HYFoundation[26729:24088514] 3 : 4
2018-02-27 13:11:41.888169+0800 HYFoundation[26729:24088389] -----
2018-02-27 13:11:41.888415+0800 HYFoundation[26729:24088389] 0 : 1
2018-02-27 13:11:41.888603+0800 HYFoundation[26729:24088389] 2 : 3
2018-02-27 13:11:41.888784+0800 HYFoundation[26729:24088389] 3 : 4
  • 小結
    • NSEnumerationOptions 是一個枚舉類型:

      typedef NS_OPTIONS(NSUInteger, NSEnumerationOptions) {
      NSEnumerationConcurrent = (1UL << 0),
      NSEnumerationReverse = (1UL << 1),
      };

      NSEnumerationConcurrent : 表示併發執行, 見上面的例子:

      2018-02-27 13:11:41.887728+0800 HYFoundation[26729:24088389] 0 : 1
      2018-02-27 13:11:41.887734+0800 HYFoundation[26729:24088493] 1 : 2
      2018-02-27 13:11:41.887748+0800 HYFoundation[26729:24088492] 2 : 3
      2018-02-27 13:11:41.887755+0800 HYFoundation[26729:24088514] 3 : 4

      [26729:24088493][26729:24088492], [26729:24088514] ,這些事變化的,即時併發執行
      NSEnumerationReverse 表示反向遍歷,即從後往前遍歷
    • -

Java forEach for循環語句

  • 方法
    `forEach` `for循環語句`
  • 例子
    ArrayList arrayList = new ArrayList();
    arrayList.add("x");
    arrayList.add("d");
    arrayList.add("b");
    arrayList.add("c");
    arrayList.add("a");

    for (Object ob: arrayList) {
        Log.e("數組", String.valueOf(ob));
    }
    Log.e("數組", "---------");
    for (int i = 0; i < arrayList.size(); i++) {
        Object ob = arrayList.get(i);
        Log.e("數組", String.valueOf(ob));
    }
    // 輸出:
    E/數組: x
    E/數組: d
    E/數組: b
    E/數組: c
    E/數組: a
    E/數組: ---------
    E/數組: x
    E/數組: d
    E/數組: b
    E/數組: c
    E/數組: a
  • 小結

      • -

JS forEach for...of for循環語句

  • 方法
    /**
     * 方法對數組的每個元素執行一次提供的函數
     * callback : 在數組每一項上執行的函數。調用時使用參數 (currentValue, index, array)。
     * thisArg : 可選參數。當執行回調 函數時用作this的值(參考對象)。
     * 返回值 : 沒有返回值,undefined.
     */
    array.forEach(callback(currentValue, index, array){
        //do something
    }, this)
    array.forEach(callback[, thisArg])

    // 具體見下面的例子
    for...of
  • 例子
    var array = [1, 5, 15, 20, 30, 100, 200]
    array.forEach(function (element, index, array) {
      console.log("index: " + index + " value: " + element)
    })
    // 輸出:
    index: 0 value: 1
    index: 1 value: 5
    index: 2 value: 15
    index: 3 value: 20
    index: 4 value: 30
    index: 5 value: 100
    index: 6 value: 200

    // 分割線 ----
     var arr = ['w', 'y', 'k', 'o', 'p'];
    for (var letter of arr) {
      console.log(letter);
    }
    // 輸出:
    w
    y
    k
    o
    p
  • 小結
    • jsfor...of 類似 oc 中的 for...in 方法,類似 javaforEach
    • -

小結

  • 相同點

    - 都可以使用 for循環語句 進行遍歷

  • 不同點

    - jsfor...of 類似 oc 中的 for...in 方法,類似 javaforEach ;都是忽略 索引 index ,直接獲取元素的值

十七、其他

OC

  • 方法
    // 在“源”數組中每個元素 和 otherArray 中的元素比較,找出第一個相同的對象
    - (nullable ObjectType)firstObjectCommonWithArray:(NSArray<ObjectType> *)otherArray;
  • 例子
    NSArray *array = @[@1, @2, @3, @4, @5];
    NSArray *otherArray = @[@3, @2];
    id object = [array firstObjectCommonWithArray:otherArray];
    NSLog(@"%@", object);

    NSArray *otherArray2 = @[@10, @11];
    id object2 = [array firstObjectCommonWithArray:otherArray2];
    NSLog(@"%@", object2);

    // 輸出:
    2
    (null)
  • 小結

      • -

Java

  • 方法

  • 例子

  • 小結

JS

  • 方法
    // 判斷 obj 是不是數組
    Array.isArray(obj)

    // 方法測試數組的所有元素是否都通過了指定函數的測試。
    arr.every(callback[, thisArg])
  • 例子
    console.log(Array.isArray([]))
    console.log(Array.isArray([1, 2]))
    console.log(Array.isArray("123"))
    console.log(Array.isArray(987))
    // 輸出:
    true
    true
    false
    false

    // 分割線 ------

    var array = [1, 5, 15]
    var result = array.every(isBigEnough)
    console.log(result)
    function isBigEnough(value, index, array) {
        return value >= 10;
    }
    // 輸出:
    false
  • 小結

      • -

小結

  • 相同點

      -
  • 不同點

最後

相同點

  1. 通過下標獲取元素 [index]
  2. 索引下標 從 0 開始,到 count - 1ocjava 超過範圍會 crash

不同點

  1. 數組的定義
    // oc / c / c++
    dataType arrayRefVar[];
    如:
    NSString *strings[3];   // c
    NSArray *arr = @[@1, @2, @3, @4]; // oc

    // java
    dataType[] arrayRefVar;
    int[] numbers = new int[3];

    // js
    var array = [1, 2, 3, 4, 5]
  1. 空值
    • oc 數組添加 nilNULL 元素 crash
    • java 數組添加 null 不會報錯,並且存在於數組中
    • js 數組添加 null undefined 不會報錯,並且存在於數組中
    // oc 添加空值 nil 會crash

    // java
    ArrayList arrayList = new ArrayList(20);
    arrayList.add(null);
    Log.e("數組", arrayList.toString());
    Log.e("數組", String.valueOf(arrayList.size()));
    // 輸出:
    E/數組: [null]
    E/數組: 1

    // js 添加 `null`  `undefined` 不會報錯
    var array = [1, 2]
    array.push(null)
    array.push(undefined)
    console.log(array)
    // 輸出:
    [1, 2, null, undefined]

oc

  1. 有序集合 : NSArrayNSMutableArray
    無序集合 :
  2. 數組的下標從 0 開始,範圍爲 0count - 1,超過範圍會 crash
  3. oc 空數組 @[] 獲取下標 0crash
  4. 數組中的元素類型是對象類型不能爲基本數據類型(如數字)

java

  1. 類有
    • ArrayList
  2. 數組中的元素類型是對象類型,也可以爲基本數據類型(如數字)

js

  1. 類有

    • Array
  2. 數組中的元素類型是對象類型,也可以爲基本數據類型(如數字)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章