In some situations we need to be sure whether the correct type of data has been passed within an array list for an argument of a method or has been received from a specific function.
Using the Vector class we can specify which type of data will be accepted in our list, allowing the insertion if only the type required was matched.
package {
public class User {
public var firstname:String = null;
public var lastname:String = null;
public var email:String = null;
public function User():void { }
}
}
2. Create a Flash File (ActionScript 3.0) within the same directory of our ActionScript class, and then type the following code:
var mylist:Vector.<User> = new Vector.<User>();
try {
mylist.push("Hello");
} catch(e:Error) {
trace(e.message);
}
Probably you will get an error message, right? Why? Cause you're trying to insert a String in our list, not a User object.
However, if you try the following:
var mylist:Vector.<User> = new Vector.<User>();
try {
var user:User = new User();
user.firstname = "Jhonatan"; user.lastname = "Rosa Jacinto"; user.email = "foo@foo.com";
mylist.push(user);
trace(mylist[0].firstname);
}
catch(e:Error) {
trace(e.message);
}
You will get "JHONATAN" in the output panel... because the object inserted was an User Object.
Very very simple, right?
One thing... if I had the following code:
var list:Vector.<DisplayObject> = new Vector.<DisplayObject>();
list.push(new MovieClip());
This code will generate an error or not?
The answer is NOO! It will work good! Why? The reason is a MovieClip object is an object of type DisplayObject, cause the MovieClip class extends from the DisplayObject class... so any MovieClip object is a DisplayObject as well.
Following this thinking, the code below will not work:
var list:Vector.<DisplayObject> = new Vector.<DisplayObject>();
list.push(new User());
Why? As explained before, our User class doesn't extend from DisplayObject or MovieClip class. So, it cannot be pushed into our list.
I hope you enjoy this tutorial.
Thanks guys and see you next time! ;)
+