简体   繁体   English

与Objective-C中的Java ArrayList等效

[英]Equivalent of Java ArrayList in Objective-C

In Objective-C what is equivalent of List<Products> cartProduct = new ArrayList(); 在Objective-C中,等效于List<Products> cartProduct = new ArrayList(); . I used NSMutableArray but that is different than Java ArrayList. 我使用了NSMutableArray,但这与Java ArrayList不同。

It sounds to me like Java ArrayLists use generics. 在我看来,Java ArrayLists使用泛型。

Objective-C does not have true support for generics. Objective-C没有对泛型的真正支持。 (Swift does. You may want to use Swift instead.) (Swift可以。您可能想要使用Swift。)

Objective-C's collection classes ( NSArray and NSMutableArray ) are heterogeneous. Objective-C的集合类( NSArrayNSMutableArray )是异构的。 They can contain a mixture of objects of different types. 它们可以包含不同类型的对象的混合物。 However, a recent addition to the language adds a very thin layer of generic support. 但是,最近对该语言的添加增加了非常薄的通用支持层。

You'd use syntax like this: 您将使用如下语法:

NSMutableArray <Products *> *cartProduct;

That syntax only adds compile-time type checking. 该语法仅添加编译时类型检查。 It tells the compiler that cartProduct is a mutable array that should only contain objects of type Products , so you get warnings when you to add/fetch objects of other types from the array, but the array will still take objects of any type at runtime. 它告诉编译器cartProduct是一个可变数组,只应包含Products类型的对象,因此,当您从该数组添加/获取其他类型的对象时,您会收到警告,但是该数组在运行时仍会接收任何类型的对象。

I found this link explaining more about Objective-C's "lightweight" support for generics. 我发现此链接解释了更多关于Objective-C对泛型的“轻量级”支持。 It seems pretty clear and well written. 看起来很清楚,写得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM