Saturday 26 March 2016

Difference between Arrays and Arraylists and Best ways to print int array,byte array,array of strings,two dimensional array and also array of array in Java

Arrays for data structure which acts as a containers that holds collections of variables of same type, in other words ,size collection of elements of the same data type. Variables stored in arrays are in continues memory locations.Before the advent of arraylists , arrays were used by programmers to store huge amount of variables 
Let us first see the differences between array lists and arrays :

  • Arraylists are dynamic in size where the size of an arraylist can grow when new elements are added while arrays are fixed in size.
  •  Arrays contains both objects as well as primitives whereas array list contains only objects.
  • Loops such as For loops are used iterate elements and iterators can be used in arralylists.
  • Arraylists ensures type safety through generics whereas arrays are homogeneous.
  • Elements are added by assignment operators and add() method is used in Arraylists to add elements. 
  • Arrays are mutli-dimensional where as Arraylists are single dimensional.
In order to consturct an array , you should new , then type of array and then specify the size of that array using open and closed  brackets. For example :
new int[6] //here type of array is int and size is 6.


Now let us see the different ways to print int array,byte array,array of strings,two dimensional array and also array of array.
  • Printing int array : 
We can use Arrays.toString(int array), for example : 
int [] odd = {3,5,7};
System.out.printing("odd numbers are"+Arrays.toString(odd));

  • Printing byte array :
Converting String into a byte array is commonly used employed in Java Cryptography Extension encryption. To convert byte array into string , create a string object and delegate the byte array to it.For example : 
String example="hello";
bytes[] bytes = example.getBytes();
String s = new String(bytes);
System.out.println("text decrypted:"+s);
  • Print an array of strings :
There are two ways of printing array of strings. One way is use a FOR loop, for example:
String [] cars=new Strings[3];
cars[0]="Ferrari";
cars[1]="maruthi";
cars[2]="Datsun";
for(int i=0;i<cars.length;i++)
{
System.out.println(cars[i]);

Another way is to use Arrays.toString().
  • Printing two dimensional array:
Here we use Arrays.deepToString, for example: 
String [][] greetings={{"hi","good morning "},{"hello"," good evening "}};
System.out.println(" planets"+Arrays.deepToString);

  • Printing array of array:
Array of same type can be stored into another array. Arrays.deepToString is used to print array of array , for example :

String []arr1=new String [] {"hi","hello"};
String []arr2=new String [] {"how are you"};
String [][] arrayOfArray=new String[][]{arr1,arr2};
System.out.println(Arrays.deepToString));


No comments:

Post a Comment