Collections: Difference between revisions
No edit summary |
|||
Line 54: | Line 54: | ||
In Python practically everything is an object, so using any of the provided structures can function as a collection. |
In Python practically everything is an object, so using any of the provided structures can function as a collection. |
||
<pre> |
<pre> |
||
collection = [0, '1'] # Lists |
collection = [0, '1'] # Lists are mutable (editable) and can be sorted in place |
||
collection = (0, 1) # Tuples |
collection = (0, 1) # Tuples are immutable (not editable) |
||
collection = {0: "zero", 1: "one"} # Dictionaries (Hash) |
collection = {0: "zero", 1: "one"} # Dictionaries (Hash) |
||
collection = set([0, '1']) # sets (Hash) |
collection = set([0, '1']) # sets (Hash) |
||
</pre> |
</pre> |
||
http://docs.python.org/tut/node7.html |
|||
==[[Ruby]]== |
==[[Ruby]]== |
Revision as of 18:17, 26 January 2007
You are encouraged to solve this task according to the task description, using any language you may know.
Collections are used to store objects and not primitive types.
Java
ArrayList arrayList = new ArrayList(); arrayList.add(new Integer(0));
JavaScript
var array = []; array.push('abc'); array.push(123); array.push(new MyClass); alert( array[2] );
var map = {}; map['foo'] = 'xyz'; //equivalent to: map.foo = 'xyz'; map['bar'] = new MyClass; //equivalent to: map.bar = new MyClass; map['1x; ~~:-b'] = 'text'; //no equivalent alert( map['1x; ~~:-b'] );
Perl
Interpreter: Perl
In perl the value of any variable can be (whats called in perl) a reference to any other simple or complex variable structure, including objects. With hashs (or associative arrays), even the key can be a reference to another variable structure.
my %hash = ( name=>'David', age=>'30' ); my $var = [ 'plain string', \%hash, [3, 2, 1], { City=>'Salt Lake City', State=>'Utah' } ];
$var is a scalar, but its value is an arrayref where the first element is just a string, the second is a hash as defined in %hash, the third is an array, the forth is another hash.
PHP
$students = array(); array_push($students, array('name' => 'Joe Smith', 'age' => 21, height=> '72.5', gpa => 3.42 ));
Python
Interpreter: Python 2.5
In Python practically everything is an object, so using any of the provided structures can function as a collection.
collection = [0, '1'] # Lists are mutable (editable) and can be sorted in place collection = (0, 1) # Tuples are immutable (not editable) collection = {0: "zero", 1: "one"} # Dictionaries (Hash) collection = set([0, '1']) # sets (Hash)
http://docs.python.org/tut/node7.html
Ruby
Ruby is a 100% object oriented language, so you can use the default Array or Hash structures as collection objects.