CSC/ECE 517 Summer 2008/wiki1 6 c9)
Array in Java:- An array is an indexed collection of items of same data type.We are not allowed to declare an array consist of multiple data type(like double and integer in same array).
Arrays in Ruby :- Arrays are the indexed collection of objects in Ruby, which is accessible using keys.The key is always an integer in a an array and the array can grow as needed.Ruby support to store different type of data to store in one array.An array can can have integer, floating point number or a string.
Declaration of array in Java:-
integer [] employee; double employee[];
The square brcaket indicates the array declaration. In Java array is an reference data type and memory is allocated to store the data in the array.The memory can be allocated with the
keyword "new".
employee = new integer [5];
It can alos be declared in one line as :-
integer employee = new integer [5];
Now the Employee array has allocated the memory to store the five integers.Unless we have initialised the array at the time of declaration we need to specify the size of an array before using it.
The indexing of an array starts from 0 to size-1.It means if the array is of size 5 then first element is stored at employee[0] and the last one is at employee[4] .In an array the elements can be initialised one by one upto the previously declared size of an array.
for ex:-
String employee = new String [5] for(int i = 0; i <5 ; i++) { employee[i] = i; }
If elements are initialised at the time of the declaration then ther is no need of specifying a size to an array.The size of an array is same as the number of initialised elements. for ex:-
String [] weekday = {Monday,Tuesday,wednesday,Thursday,friday,Saturday,Sunday};
In this example the size of an array is 7.
Declaration of array in Ruby:- ruby does not require to declare the size of
an array.
x = ['cat' , 5 ,6 ,'fly'] y = ['apple' , 'orange', 'pineapple']
An array can be declared with the new keyword also. for ex:
num = array.new
num << 3
num << 4
Now that array num has two element 3 and 4.
The indexing of an array starts from 0 and goes up to the size-1. Ruby supports the negative indexing in array.Negative index counts backward and x[-1] is same as referencing the last element of x.
Adding more element in the existing array :- Java does not allow to add more elements than the size of an existing array.If user is interested to add more items,the size of the array needs to be increased. Ruby is very flexible with adding the number of elements in the array of any data type with no limit on size.Ruby is not bound to declare the size of an array before using it.For ex:-
num = [1 ,2 ,4, 3, 5]
num + ["apple", "cycle"]
num =>[1, 2, 4 , 3,"5", "apple", "cycle"]
Another way to add the element is :-
num.push "berry"
It adds the berry at last in the array.
num =>[1, 2, 4 , 3,"5", "apple", "cycle", "Berry"]
Adding an element at a particular index is num[index number] = item
or num.insert(2,7)
num =>[1, 2,7,4,3,5]