集合初级
———- android培训、java培训、期待与您交流! ———-
引子
我们知道C语言的数组能够存储一组相同的数据类型,比如
char []能够存储一组字符int []存储一组数字 Object[]能存储一组相同的对象,但是如果我想存储一组不同的对象,或者是一组无序的对象,又或者是一组有对应关系如 中国—zh这样关系的对象怎么办呢?
答案是用集合类来实现
NSArray and NSMutableArray
//OC数组不能存放nil
//OC数组只能存放OC对象,不能存放非OC对象类型,如(int,struct,enum...)
//NSArray *array=[NSArray array]; // 这个array永远是空数组,此类方法用于NSMutableString
NSArray *array2 = [NSArray arrayWithObject:@"jack"];
NSArray *array3 = [NSArray arrayWithObjects:@"jack",@"rose",nil];
NSArray *array4 = @[@"jack",@"rose"]; // Xcode特性,翻译成面的那一句话 只返回NSArray NSMutableArray *array5 = @[@"jack",@"rose"];错误写法
NSLog(@"%@",array3.count); // 打印为2 ,计算数组的长度
NSLog(@"%@",[array3 objectAtIndex:1]);// 打印rose,OC数组array3下标为1的元素
NSlog(@"%@",array3[1]); // Xcode特性 翻译成上面的那一句话
可变数组
// 创建空数组
NSMutableArray *ary1 = [NSMutableArray array];
// 添加元素
[ary1 addObject:@"a"];
[ary1 addObject:@"d"];
NSLog(@"ary1 %@",ary1);
//添加多个元素
NSMutableArray *ary2 = [NSMutableArray array];
[ary2 addObjectsFromArray:ary1];
NSLog(@"ary2 %@",ary2);
用block遍历数组
Person *p = [[Person alloc] init];
NSArray *array = @[p, @"rose", @"jack"];
[array enumerateObjectsUsingBlock:
// 每遍历到一个元素,就会调用一次block
// 并且当前元素和索引位置当做参数传给block
^(id obj, NSUInteger idx, BOOL *stop)
{
NSLog(@"%ld - %@", idx, obj);
if (idx == 0)
{
// 停止遍历
*stop = YES;
}
}];
NSSet and NSMutableSet
不可变集合NSSet
NSSet *s1 = [NSSet setWithObjects:@"jack1",@"jack2",@"jack3",@"jack4",nil];
NSString *str = [s1 anyObject]; // 随机取出一个元素
NSLog(@"%@",str);
可变集合NSMutableSet
//创建初始化可变集合
NSMutableSet *mutableSet1=[NSMutableSet Set];//空集合
NSMutableSet *mutableSet2=[NSMutableSet setWithObjects:@"111",@"222", nil];
NSMutableSet *mutableSet3=[NSMutableSet setWithObjects:@"sky",@"2", nil];
//两个集合去除相同的部分
[mutableSet2 minusSet:mutableSet3]; NSLog(@"%@",mutableSet2);
//求两个集合相同的元素
[mutableSet2 intersectSet:mutableSet3]; NSLog(@"%@",mutableSet2);
//两个集合进行合并
[mutableSet2 unionSet:mutableSet3]; NSLog(@"%@",mutableSet2);
和NSArray对比
共同点:
- 都是集合,都能存放多个OC对象
- 只能存放OC对象,不能存放非OC对象类型(基本数据类型:int、char、float、struct、enum…)
- 本身长度都不可变,有一个可变的子类
不同点:
NSArray有序,NSSet无序
NSDictionary and NSMutableDictionary
NSDictionary
NSDictionary用于键值映射相当于Java中的Map集合
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"One",@"1",@"Two",@"2",@"Three",@"3",nil];
NSString *string = [dictionary objectForKey:@"One"];
NSLog(@"string:%@",string);
NSLog(@"dictionary:%@",dictionary);
[dictionary release];
NSMutableDictionary
// 创建
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
// 添加字典
[dictionary setObject:@"One" forKey:@"1"];
[dictionary setObject:@"Two" forKey:@"2"];
[dictionary setObject:@"Three" forKey:@"3"];
[dictionary setObject:@"Four" forKey:@"4"];
// 删除指定的字典
[dictionary removeObjectForKey:@"3"];