利用數組實現簡化的List

前言

複習下數組的使用方式,仿照List用oc實現下數組的增刪改查

功能

  1. 初始化時給定數組的容量
  2. 插入數據
  3. 刪除數據
  4. 根據下標返回數據

代碼

  1. 聲明頭文件
    ​ 頭文件中包含了6個對象方法,如下:

    • initWithCapacity
      用於初始化數組容量

    • find
      根據下標查找數據

    • remove
      根據下標刪除數據

    • insert
      根據下標插入數據

    • add
      尾部追加數據

    • printAll
      打印所有數據

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface CustomArray : NSObject

 //初始化方法
- (instancetype) initWithCapacity: (NSUInteger) capacity;
//根據下標返回對應的值
- (id)find:(NSUInteger) index;
//根據下標刪除對應的值
- (void)remove:(NSUInteger) index;
//插入指定位置
- (void)insert:(id)anObject atIndex:(NSUInteger) index;
//尾部追加
- (void)add: (id)anObject;
//打印所有
- (void)printAll;

@end

NS_ASSUME_NONNULL_END
  1. 各個方法的實現

    1. 定義成員變量

      @implementation MyArray
      {
        	//可變數組
          @private
          NSMutableArray *_data;
        	//起始容量
          NSUInteger _capacity;
        	//數組中存儲的數據大小
          NSUInteger _count;
      }
      
    2. initWithCapacity

      初始化,傳入起始容量。

      - (instancetype)initWithCapacity:(NSUInteger)capacity {
          self = [super init];
          if (self) {
              _data = [NSMutableArray arrayWithCapacity:capacity];
              _capacity = capacity;
              _count = 0;
          }
          return self;
      }
      
    3. find

      根據下標返回元素

      - (id)find:(NSUInteger)index {
          if (index >= _count) {
              return nil;
          }
          return _data[index];
      }
      
    4. remove

      根據下標,刪除數據

      - (void)remove:(NSUInteger)index {
          if (index >= _count) {
              [NSException raise:NSRangeException format:@"Index out of rang."];
          }
          for (NSUInteger i = index; i < _count - 1; i++) {
              _data[i] = _data[i + 1];
          }
          _count--;
      }
      

      刪除數據時,後邊的元素依次向前移一個位置,同時,總數-1

    5. insert

      根據下標,插入數據

      - (void)insert:(id)anObject atIndex:(NSUInteger)index {
          if (index >= _count || _capacity == _count) {
              [NSException raise:NSRangeException format:@"Index out of range."];
          }
          for (NSUInteger i = _count - 1; i >= index; i--) {
              _data[i + 1] = _data[i];
          }
          _data[index] = anObject;
          _count++;
      }
      
      

      插入數據時,後邊的元素依次向後一個位置,同時,總數+1

    6. add

      添加一個數據

      - (void)add:(id)anObject {
          if (_count == _capacity) {
              [NSException raise:NSRangeException format:@"Array is full."];
          }
          [_data addObject:anObject];
          _count++;
      }
      
    7. printAll

      - (void)printAll {
          for (id obj in _data) {
              NSLog(@"%@",obj);
          }
      }
      

所有的操作,一定要注意**下標**的判斷!

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