Original article

  • Built-in arrays
  • Javascript Arrays(Javascript only)
  • ArrayLists
  • Hashtables
  • Generic Lists
  • Generic Dictionaries
  • 2D Arrays

All types of collections share a few common features:

  • You can fill them with objects, and read back the values that you put in.
  • You can ‘iterate’ through them, which means you can create a loop which runs the same piece of code against each item in the collection.
  • You can get the length of the collection.
  • For most collections – but not all – you can arbitrarily add and remove items at any position, and sort their contents.

Built-in Arrays

The most basic type of array, available in both JS and C#, is the built-in array. The main shortcoming of built-in arrays is that they have a fixed-size (which you choose when you declare the array), however this shortcoming is balanced by their very fast performance. For this reason, built-in arrays are the best choice if you need the fastest performance possible from your code (for example, if you’re targeting iPhone). If there is a fixed and known number of items that you want to store, this is the best choice.

It’s also common to use this type of array if you have a varying number of items to store, but you can decide on a ‘maximum’ for the number of objects that you’ll need. You can then leave some of the elements in the array null when they’re not required, and design your code around this. For example, for the bullets in a shooting game, you may decide to use an array of size 50, allowing a maximum of 50 active bullets at any one time.

This type of array is also useful because it’s one of the type osf array which show up in Unity’s inspector window. This means that a built-in array ia good choice if you want to populate its contents in the Unity editor, by dragging and dropping references.

It’s also usually the type of array you get back from Unity functions, if you use a function which may return a number of objects, such as GetComponentsInChildren.

Built-in arrays are declared by specifying the type of object you want to store, followed by brackets. Eg:

Basic Declaration & Use:

C#

// declaration
TheType[] myArray = new TheType[lengthOfArray]; // declaration example using ints
int[] myNumbers = new int[]; // declaration example using GameObjects
GameObject[] enemies = new GameObject[]; // get the length of the array
int howBig = myArray.Length; // set a value at position i
myArray[i] = newValue; // get a value from position i
TheType thisValue = myArray[i];

Javascript

// declaration
var myArray = new TheType[lengthOfArray]; // declaration example using ints
var myNumbers = new int[10]; // declaration example using GameObjects
var enemies = new GameObject[16]; // get the length of the array
var howBig = enemies.Length; // set a value at position i
myArray[i] = newValue; // get a value from position i
var thisValue = myArray[i]

Full MSDN Documentation for Built-in Array

Some direct links to useful Functions/Methods of Built-in Arrays:

IndexOfLastIndexOfReverseSortClearClone

Javascript Arrays

The ‘Javascript Array’ in unity is a special class that is provided in addition to the standard .net classes. You can only declare them if you are using a Javascript syntax script – you can’t declare them in C#. Javascript arrays are dynamic in size, which means you don’t have to specify a fixed size. You can add and remove items to the array, and the array will grow and shrink in size accordingly. You also don’t have to specify the type of object you want to store. You can put objects of any type into a Javascript array, even mixed types in the same array.

Javascript arrays are therefore somewhat easier to use than built-in arrays, however they are a bit more costly in terms of performance (although performance cost here is only worth worrying about if you are dealing with very large numbers of objects, or if you’re targeting the iPhone). Another potential downside is that there are certain situations where you need to use explicit casting when retrieving items because of their ‘untyped’ nature – despite Javascript’s dynamic typing.

Basic Declaration & Use:
(Javascript Only)

// declaration
var myArray = new Array(); // add an item to the end of the array
myArray.Add(anItem); // retrieve an item from position i
var thisItem = myArray[i]; // removes an item from position i
myArray.RemoveAt(i); // get the length of the Array
var howBig = myArray.length;

Full Unity Documentation for Javascript Array

Some direct links to useful Functions/Methods of Unity’s Javascript Arrays:

ConcatJoinPushAddPopShiftRemoveAtUnshiftClearReverse,Sort

ArrayLists

The ArrayList is a .Net class, and is very similar to the Javascript Array mentioned previously, but this time available in both JS and C#. Like JS Arrays, ArrayLists are dynamic in size, so you can add and remove items, and the array will grow and shrink in size to fit. ArrayLists are also untyped, so you can add items of any kind, including a mixture of types in the same ArrayList. ArrayLists are also similarly a little more costly when compared to the blazingly fast performance of built-in arrays. ArrayLists have a wider set of features compared to JS Arrays, although neither of their feature sets completely overlaps the other.

Basic Declaration & Use:

Javascript

// declaration
var myArrayList = new ArrayList(); // add an item to the end of the array
myArrayList.Add(anItem); // change the value stored at position i
myArrayList[i] = newValue; // retrieve an item from position i
var thisItem : TheType = myArray[i]; (note the required casting!) // remove an item from position i
myArray.RemoveAt(i); // get the length of the array
var howBig = myArray.Count;

C#

// declaration
ArrayList myArrayList = new ArrayList(); // add an item to the end of the array
myArrayList.Add(anItem); // change the value stored at position i
myArrayList[i] = newValue; // retrieve an item from position i
TheType thisItem = (TheType) myArray[i]; // remove an item from position i
myArray.RemoveAt(i); // get the number of items in the ArrayList
var howBig = myArray.Count;

Full MSDN Documentation for ArrayList

Some direct links to useful Functions/Methods of the ArrayList:

AddInsertRemoveRemoveAtClearCloneContainsIndexOf,LastIndexOfGetRangeSetRangeAddRangeInsertRange,RemoveRangeReverseSortToArray

Hashtables

A Hashtable is a type of collection where each item is made up of a “Key and Value” pair. It’s most commonly used in situations where you want to be able to do a quick look-up based on a certain single value. The piece of information that you use to perform the look-up is the ‘key’, and the object that is returned is the “Value”.

If you are familiar with web development, it’s similar to the type of data in a GET or POST request, where every value passed has a corresponding name. With a Hashtable however, both the keys and the values can be any type of object. For most practical applications, it’s usually the case that your keys are going to be all the same type (eg, strings) and your values are likely to be all of the same type too (eg, GameObjects, or some other class instance). Compare with ArrayLists, because Hashtable keys and values are untyped, you usually have to deal with the type casting yourself when you retrieve values from the collection.

Hashtables are designed for situations where you want to be able to quickly pick out a certain item from your collection, using some unique identifying key – similar to the way you might select a record from a database using an index, or the way you might pick out the contact details of a person using their name as the ‘unique identifier’.

Basic Declaration & Use:

Javascript

// declaration
var myHashtable = new Hashtable(); // insert or change the value for the given key
myHashtable[anyKey] = newValue; // retrieve a value for the given key
var thisValue : ValueType = myHashtable[theKey]; (note the required type casting) // get the number of items in the Hashtable
var howBig = myHashtable.Count; // remove the key & value pair from the Hashtable, for the given key.
myHashtable.Remove(theKey);

C#

// declaration
Hashtable myHashtable = new Hashtable(); // insert or change the value for the given key
myHashtable[anyKey] = newValue; // retrieve a value for the given key
ValueType thisValue = (ValueType)myHashtable[theKey]; // get the number of items in the Hashtable
int howBig = myHashtable.Count; // remove the key & value pair from the Hashtable, for the given key.
myHashtable.Remove(theKey);

Full MSDN Documentation for Hashtable Members

Some direct links to useful Functions/Methods of the HashTable:

AddRemoveContainsKeyContainsValueClear

Generic List

First of all corrections to the original article: Generics are not supported at all on iPhone, (generics are now supported in Unity 3 iOS!). In addition, you can’t declare Generics in unity’s Javascript, (you can now declare generics in Unity 3′s Javascript!).

The Generic List (also known as List) is similar to the JS Array and the ArrayList, in that they have a dynamic size, and support arbitrary adding, getting and removing of items. The significant difference with the Generic List (and all other ‘Generic’ type classes), is that you explicitly specify the type to be used when you declare it – in this case, the type of object that the List will contain.(与ArrayList基本相同,但是唯一区别是显示的表明T)

Once you’ve declared it, you can only add objects of the correct type – and because of this restriction, you get two significant benefits:

  • no need to do any type casting of the values when you come to retrieve them.
  • performs significantly faster than ArrayList

This means that if you were going to create an ArrayList, but you know that you will only be putting objects of one specific type of object into it, (and you know that type in advance) you’re generally better off using a Generic List. For me, this tends to be true pretty much all the time.

The generic collections are not part of the standard System.Collections namespace, so to use them, you need to add a line a the top of any script in which you want to use them:

using System.Collections.Generic;

Basic Declaration & Use:

JS:

// declaration
var myList = new List.<Type>(); // a real-world example of declaring a List of 'ints'
var someNumbers = new List.<int>(); // a real-world example of declaring a List of 'GameObjects'
var enemies = new List.<GameObject>(); // add an item to the end of the List
myList.Add(theItem); // change the value in the List at position i
myList[i] = newItem; // retrieve the item at position i
var thisItem = List[i]; // remove the item from position i
myList.RemoveAt(i);

C#:

// declaration
List<Type> myList = new List<Type>(); // a real-world example of declaring a List of 'ints'
List<int> someNumbers = new List<int>(); // a real-world example of declaring a List of 'GameObjects'
List<GameObject> enemies = new List<GameObject>(); // add an item to the end of the List
myList.Add(theItem); // change the value in the List at position i
myList[i] = newItem; // retrieve the item at position i
Type thisItem = List[i]; // remove the item from position i
myList.RemoveAt(i);

Unity3d example:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System; public class GenerciList : MonoBehaviour
{ List<String> phraseList = new List<String>(); void OnGUI()
{
int i = ;
foreach (String str in phraseList)
{
if (GUI.Button(new Rect(, * i, , ), str))
{
Debug.Log("Box #" + i + " is working");
}
i++;
}
}
void Update()
{
if (Input.GetKeyUp("z"))
{
phraseList.Add("Test string 1");
phraseList.Add("Test string 2");
phraseList.Add("Test string 3");
foreach (String str in phraseList)
{
Debug.Log(str);
}
}
}
}

Full MSDN Documentation for Generic List

Some direct links to useful Methods of the Generic List:

AddInsertRemoveRemoveAllRemoveAtContainsIndexOf,LastIndexOfReverseSortClearAddRangeGetRangeInsertRange,RemoveRangeToArray

Generic Dictionary

This is another Generic class, so the same restrictions used to apply to old version of Unity, since now Unity 3, generics are now supported in Unity iOS and in Unity’s Javascript!.

The Generic Dictionary is to the Hashtable what the Generic List is to the ArrayList. The Generic Dictionary provides you with a structure for quickly looking up items from a collection (like the Hashtable), but it differs from the Hashtable in that you must specify explictly the types for the Keys and Values up-front, when you declare it. Because of this, you get similar benefits to those mentioned in the Generic List. Namely, no annoying casting needed when using the Dictionary, and a significant performance increase compared to the Hashtable.

Because you Generic Dictionary, you need to specify the types for both the Keys and the Values, the declaration line can end up a little long and wordy. However, once you’ve overcome this they are great to work with!

Again, to use this, you’ll need to include the Generic Collections package by including this line at the top of your script:

using System.Collections.Generic;

Basic Declaration & Use:

JS:

// declaration:
var myDictionary = new Dictionary.<KeyType,ValueType>(); // and a real-world declaration example (where 'Person' is a custom class):
var myContacts = new Dictionary.<string,Person>(); // insert or change the value for the given key
myDictionary[anyKey] = newValue; // retrieve a value for the given key
var thisValue = myDictionary[theKey]; // get the number of items in the Hashtable
var howBig = myDictionary.Count; // remove the key & value pair from the Hashtable, for the given key.
myDictionary.Remove(theKey);

C#:

// declaration:
Dictionary<KeyType,ValueType> myDictionary = new Dictionary<KeyType,ValueType>(); // and a real-world declaration example (where 'Person' is a custom class):
Dictionary<string,Person> myContacts = new Dictionary<string,Person>(); // insert or change the value for the given key
myDictionary[anyKey] = newValue; // retrieve a value for the given key
ValueType thisValue = myDictionary[theKey]; // get the number of items in the Hashtable
int howBig = myDictionary.Count; // remove the key & value pair from the Hashtable, for the given key.
myDictionary.Remove(theKey);

Full MSDN Documentation for Dictionary(TKey,TValue)

Some direct links to useful Methods of the Generic Dictionary:

AddRemoveContainsKeyContainsValueClear

2D Array

So far, all the examples of Arrays and Collections listed above have been one-dimensional structures, but there may be an occasion where you need to place data into an array with more dimensions. A typical game-related example of this is a tile-based map. You might have a ‘map’ array which should have a width and a height, and a piece of data in each cell which determines the tile to display. It is also possible to have arrays with more than two dimensions, such as a 3D array or a 4D array – however if you have a need for a 3D or 4D array, you’re probably advanced enough to not require an explanation of how to use them!

There are two methods of implementing a multi-dimensional array. There are “real” multi-dimensional arrays, and there are “Jagged” arrays. The difference is this:

With a “real” 2D array, your array has a fixed “width” and “height” (although they are not called width & height). You can refer to a location in your 2d array like this: myArray[x,y].

In contrast, “Jagged” arrays aren’t real 2D arrays, because they are created by using nested one-dimensional arrays. In this respect, what you essentially have is a one-dimensional outer array which might represent your ‘rows’, and each item contained in this outer array is actually an inner array which represents the cells in that row. To refer to a location in a jagged array, you would typically use something like this:

myArray[y][x].

Usually, “real” 2D arrays are preferable, because they are simpler to set up and work with, however there are some valid cases for using jagged arrays. Such cases usually make use of the fact that – with a jagged array – each ‘inner’ array doesn’t have to be the same length (hence the origin of the term “jagged”).

Another important correction is that Unity’s Javascript used to have no support for creating 2D arrays – however since Unity 3.2, Unity’s JS now supports this.

Basic Declaration & Use of “real” 2D arrays:

JS:

// declaration:

// a 16 x 4 array of strings
var myArray = new string[16,4]; // and a real-world declaration example (where 'Tile' is a user-created custom class): // create an array to hold a map of 32x32 tiles
var map = new Tile[32,32]; // set the value at a given location in the array
myArray[x,y] = newValue; // retrieve a value from a given location in the array
var thisValue = myArray[x,y]; // get the length of 1st dimension of the array
var width = myArray.GetUpperBound(0); // get the length of 2nd dimension of the array
var length = myArray.GetUpperBound(1);

C#:

// declaration:

// a 16 x 4 array of strings
string[,] myArray = new string[,]; // and a real-world declaration example (where 'Tile' is a user-created custom class): // create an array to hold a map of 32x32 tiles
Tile[,] map = new Tile[,]; // set the value at a given location in the array
myArray[x,y] = newValue; // retrieve a value from a given location in the array
ValueType thisValue = myArray[x,y]; // get the length of 1st dimension of the array
int width = myArray.GetUpperBound(); // get the length of 2nd dimension of the array
int length = myArray.GetUpperBound();

Arrays, Hashtables and Dictionaries的更多相关文章

  1. .net Framework Class Library(FCL)

    from:http://msdn.microsoft.com/en-us/library/ms229335.aspx 我们平时在VS.net里引用的那些类库就是从这里来的 The .NET Frame ...

  2. Faster, more memory efficient and more ordered dictionaries on PyPy

    Faster, more memory efficient and more ordered dictionaries on PyPy https://morepypy.blogspot.com/20 ...

  3. 【c#技术】一篇文章搞掂:Newtonsoft.Json Json.Net

    一.介绍 Json.Net是一个.Net高性能框架. 特点和好处: 1.为.Net对象和JSON之间的转换提供灵活的Json序列化器: 2.为阅读和书写JSON提供LINQ to JSON: 3.高性 ...

  4. Swift 学习- 05 -- 集合类型

    // 集合类型 // swift 提供 Arrays , Sets 和 Dictionaries 三种基本的集合类型用来存储数据 , 数组(Arrays) 是有序数据的集, 集合(Sets)是无序无重 ...

  5. 把功能强大的Spring EL表达式应用在.net平台

    Spring EL 表达式是什么? Spring3中引入了Spring表达式语言—SpringEL,SpEL是一种强大,简洁的装配Bean的方式,他可以通过运行期间执行的表达式将值装配到我们的属性或构 ...

  6. SQL Database for Modern Developers

    好书分享,面向开发者的Azure SQL Database最佳实践,也适用SQL Server 2016以上的版本.应对不同场景使用的数据库功能,包括内存表,列存储表,非聚集列存储索引,JSON等等. ...

  7. IOS学习之路十九(JSON与Arrays 或者 Dictionaries相互转换)

    今天写了个json与Arrays 或者 Dictionaries相互转换的例子很简单: 通过 NSJSONSerialization 这个类的 dataWithJSONObject: options: ...

  8. IOS开发之把 JSON 数据转化成 Arrays 或者 Dictionaries

    1 前言通过 NSJSONSerialization 这个类的 JSONObjectWithData:options:error:方法来实现,把JSON 数据解析出来放在数据或者字典里面保存. 2 代 ...

  9. Java程序员的日常—— Arrays工具类的使用

    这个类在日常的开发中,还是非常常用的.今天就总结一下Arrays工具类的常用方法.最常用的就是asList,sort,toStream,equals,copyOf了.另外可以深入学习下Arrays的排 ...

随机推荐

  1. replicate-do-db参数引起的MySQL复制错误及处理办法

    replicate-do-db配置在MySQL从库的my.cnf文件中,可以指定只复制哪个库的数据.但是这个参数有个问题就是主库如果在其他的schema环境下操作,其binlog不会被从库应用,从而出 ...

  2. 【转】XCode环境变量及路径设置 -- 待学习

    原文网址:http://www.cnblogs.com/oc-bowen/p/5140541.html 一般我们在xcode里面配置包含工程目录下头文件的时候,都要关联着相对路径和绝对路径,如果只是自 ...

  3. 【转】IOS开发:[1]Xcode5界面入门

    ios开发离不开xcode,这篇以xcode5界面来介绍一下xcode的界面都有哪些内容. 工具/原料 xcode5 整体来看区域有哪些? 1 首先我们先整体来看一下,xcode5界面可以分为五大主要 ...

  4. [再寄小读者之数学篇](2014-11-19 $\sin x/x$ 在 $(0,\pi/2)$ 上递增)

    $$\bex \frac{\sin x}{x}\nearrow. \eex$$ Ref. [Proof Without Words: Monotonicity of $\sin x/x$ on $(0 ...

  5. Safari on iOS 7 中Element.getClientRects的Bug

    在Safari浏览器中,DOMElement和Range对象都提供了getBoundingClientRect方法和getClientRects方法.顾名思义,getBoundingClientRec ...

  6. [讲座]【项目收集】“清流资本”互联网金融沙龙——颠覆者的创新与机会

    [项目收集]"清流资本"互联网金融沙龙--颠覆者的创新与机会 2014年4月19日 14:00 - 2014年4月19日 17:00 北京海淀北京海淀区海淀图书城南侧3W咖啡 限额 ...

  7. 网站压力测试工具-Webbench源码笔记

    Ubuntu 下安装使用 1.安装依赖包CTAGS sudo apt-get install ctage 2.下载及安装 Webbench http://home.tiscali.cz/~cz2105 ...

  8. shell 中awk、if while 例子

    1.if while命令写在一行中while read a b;do echo $a $b;done < aa.txt12 13 14cat aa.txt12 13 14if [[ $i -eq ...

  9. C#语言基础01

    Console.WriteLine("hello"); Console.ReadKey();// 按一个按键继续执行 string s=Console.ReadLine();//用 ...

  10. MVC&&MVP

    Classic MVC Classic MVC 大概上世纪七十年代,Xerox PARC的Trygve提出了MVC的概念. 并应用在Smalltalk系统中,为了和其它类型的MVC加以区分,历史上习惯 ...