- Home /
How to declare an arrayList? And when to use a regular array, VS Array, VS List, VS ArrayList?
Keep getting errors like wasn't expecting 'new', etc.
I read the documentation here: http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use%3F
However when I do (in unityscript):
var someVar: new ArrayList();
it doesnt work.
I also tried:
var someVar: new ArrayList{};
And:
private var someVar: new ArrayList();
And:
function Start()
var someVar: new ArrayList();
And:
var someVar: ArrayList();
While some of these are silly.. the question remains.. what the heck is happening? I haven't used these before so bare with me.
Another thing is that it's really confusing that there's so many other collections out there (mentioned in the title) - when to use what?
Thanks.
Well I didn't figure it out, but I reread some things and I'm just going to go with generic list.
I also usually prefer the generic lists, but just for the records, maybe you should try this:
var someVar = new ArrayList();
i.e. you can't use the 'new' keyword after the : because a type is expected after the : and not a keyword.
If you want all items in your list to be of a single type, then the generic list would be O$$anonymous$$, but the ArrayList comes in useful if your items were of different types.
Answer by vexe · Oct 20, 2013 at 12:20 PM
Never use the Array
or ArrayList
classes as they store objects
instead of explicit types, so you'll need to cast values back and forth so you'll fall into boxing and unboxing. Either use a regular array, or a generic list. See this. - And don't freak out when you hear, "LISTS ARE BETTER THAN ARRAYS, YOU SHOULD ALWAYS USE LISTS!!" This drives me crazy. - I see a lot of confusion here when the word 'array' is mentioned, people think of Array
class when they hear it, not sure why. Regular arrays are faster than generic lists (but no a whole lot)
When to use regular array and when to use a list? - Use a regular array when you know how many elements you need and you don't expect that number to change (via adding, removing), use it in places where high performance is required. Use a generic list if you need more dynamic acrobatics, like inserting an element at a certain index, removing an element, appending to the end of the list, etc. There's tons of fun stuff you could do with List
.
[regular array]
[C#]
GameObject[] objects = new GameObject[SIZE];
[JS]
objects : GameObject[] = new GameObject[SIZE];
[generic list]
[C#]
List<GameObject> objects = new List<GameObject>();
[JS]
var objects : List.<GameObject> = new List.<GameObject>();
EDIT: Here's a nice cheat sheet I found, on the complexity and performance of different data structures performing different operations - Check it out!
I converted my answer to comment and choose yours, fittingly. Thanks!
Welcome :) I saw you closing the question without getting fulfilled, so I thought I reopen it and post something. Glad I helped.