Sunday, April 1, 2012

Arrays


Declaration of Arrays
---------------------------

One Dimensional Arrays:
-----------------------------

form1
-------
          datatype arrname[];

form2
-------
          datatype [] arrname;

Examples:
          int number[];
          float average[];
          int[] count;
          float[] marks;

Creation of Arrays:
-----------------------
We need to create in the memory.
syntax:
          arrayname=new type[size];

Examples:
          number=new int[5];
          average=new float[10];

Combine the two steps- declaration and creation
syntax:
          datatype arrname[]=new datatype[size];
ex:
          int number[]=new int[15];
Initialization of Arrays:
----------------------------
syntax:
          datatype arrayname[]={list of values};
          ex:
          int number[]={34,45,56,67};
          It is possible to assign an array object to another.
          int a[]={2,43,5};
          int b[];
          b=a;

get and print the array elements
-------------------------------------
import java.io.*;
class array1
{
          public static void main(String args[])throws IOException
          {
                   DataInputStream din=new DataInputStream(System.in);
                   int a[]=new int[10];
                   int n,i;
                   System.out.println("How many numbers :");
                   n=Integer.parseInt(din.readLine());
                   System.out.println("Enter  "+n+" Numbers :");
                   for(i=0;i<n;i++)
                   a[i]=Integer.parseInt(din.readLine());
                   System.out.println("Array elements are :");
                   for(i=0;i<n;i++)
                             System.out.println(a[i]);
                   }
          }


Average an array of values.
--------------------------------
import java.io.*;
class array2
{
          public static void main(String args[])throws IOException
          {
                   DataInputStream din=new DataInputStream(System.in);
                   int a[]=new int[10];
                   int n,i,result=0;
                   System.out.println("How many numbers :");
                   n=Integer.parseInt(din.readLine());
                   System.out.println("Enter  "+n+" Numbers :");
                   for(i=0;i<n;i++)
                   {
                   a[i]=Integer.parseInt(din.readLine());
                   result=result+a[i];
                    }

                   System.out.println("Average is "+result/n);

                   }
          }

Sorting n numbers
----------------------
import java.io.*;
class array3
{
          public static void main(String args[])throws IOException
          {
                   DataInputStream din=new DataInputStream(System.in);
                   int a[]=new int[10];
                   int n,i,j,t;
                   System.out.println("How many numbers :");
                   n=Integer.parseInt(din.readLine());
                   System.out.println("Enter  "+n+" Numbers :");
                   for(i=0;i<n;i++)
                   a[i]=Integer.parseInt(din.readLine());
                   for(i=0;i<n-1;i++)
{
                             for(j=i+1;j<n;j++)
                             {
                                       if(a[i]>a[j])
                                       {
                                      t=a[i];
                                      a[i]=a[j];
                                      a[j]=t;
                                       }
                             }
}
                   System.out.println("Sorted list :");
                   for(i=0;i<n;i++)
                             System.out.print(a[i]+"   ");
                   }
          }

Multidimensional Arrays
----------------------------
Syntax:
          datatype arrname[][]=new datatype[][];
ex:
          int twoD[][]=new int[4][5];
get and print the matrix element
--------------------------------------
import java.io.*;
class array4
{
          public static void main(String args[])throws IOException
          {
                   DataInputStream din=new DataInputStream(System.in);
                   int a[][]=new int[2][2];
                   int n,i,j;
                   System.out.println("Enter 4 Elements:");
                   for(i=0;i<2;i++)
                   for(j=0;j<2;j++)
                   a[i][j]=Integer.parseInt(din.readLine());
                   System.out.println("Matrix Elements are :");
                   for(i=0;i<2;i++)
                   {
                             System.out.print("\n");
                             for(j=0;j<2;j++)
                             {
                             System.out.print(a[i][j]+"\t");
                             }
                    }
}
}

Manually allocate differing size second dimensions
-------------------------------------------------------------
import java.io.*;
class array5
{
          public static void main(String args[])throws IOException
          {
                   DataInputStream din=new DataInputStream(System.in);
                   int a[][]=new int[4][];
                   a[0]=new int[1];
                   a[1]=new int[2];
                   a[2]=new int[3];
                   a[3]=new int[4];
                   int i,j,k=0;

                   for(i=0;i<4;i++)
{
                             for(j=0;j<i+1;j++)
{
                             a[i][j]=k;
                             k++;
                             }
}

                    for(i=0;i<4;i++)
                   {
                             System.out.print("\n");
                             for(j=0;j<i+1;j++)
                             {
                             System.out.print(a[i][j]+"\t");
                             }
                    }
}
}

Three D Matrix:
--------------------
import java.io.*;
class array4
{
          public static void main(String args[])throws IOException
          {
                   DataInputStream din=new DataInputStream(System.in);
                   int a[][][]=new int[3][4][5];
                   int i,j,k;
                   for(i=0;i<3;i++)
                   for(j=0;j<4;j++)
                   for(k=0;k<5;k++)
                   a[i][j][k]=i*j*k;

                   for(i=0;i<3;i++)
{

                   for(j=0;j<4;j++)
{
                   for(k=0;k<5;k++)
                   System.out.print(a[i][j][k]+"   ");
                   System.out.println();
          }
          System.out.println();
}
}
}

length
-------
it will always hold the size of the array.
//This program demonstrates the length array member.
class Length
{
          public static void main(String args[])
{
                   int a1[]=new int[10];
                   int a2[]={3,45,56,67,-45,23,-9};
                   int a3[]={5,4,3,23};

                   System.out.println("length of a1 is "+a1.length);
                   System.out.println("length of a2 is "+a2.length);
                   System.out.println("length of a3 is "+a3.length);
          }
}
---------------------
class CommandLine
{
          public static void main(String args[])
{
                   for(int i=0;i<args.length;i++)
                   System.out.println("args["+i+"]="+args[i]);
          }
}

Vectors
----------
The Vector class contained in the java.util package.  This class can be used to create a generic dynamic array known as vector that can hold objects of any type and any number.  The objects do not have to be homogeneous.
ex:
          Vector intVect=new Vector();//declaring without size
          Vector list=new Vector(5);
Vectors possess a number of advantages over arrays.
1.  It is convenient to use vectors to store objects.
2.  A vector can be used to store a list of objects that may vary in size.
3.  We can add and delete objects from the list as and when required.
we cannot directly store simple data type in a vector, we can only store objects.  Therefore we need to convert simple types to objects.This can be done using the wrapper classes

Important Vector Methods
Method Call                                                Task performed
list.addElement(item)        Adds the item specified to the list at the end
list.elementAt(10)             Gives the name of the 10th object
list.size()                           Gives the number of objects present
list.removeElement(item)    Removes the specified item from the list
list.removeElementAt(n)   Removes the item stored in the nth position of       the list
list.removeAllElements()            Removes all the elements in the list
list.copyInto(array)              Copies all items from list to array.
list.insertElementAt(item,n) Inserts the item at nth position

Working with vectors and arrays
---------------------------------------
import java.util.*;
class LanguageVector
{
 public static void main(String args[])
{
          Vector list=new Vector();
          int length=args.length;
          for(int i=0;i<length;i++)
          {
                   list.addElement(args[i]);
          }
          list.insertElementAt("JAVA",2);
          int size=list.size();
          String listArray[]=new String[size];
          list.copyInto(listArray);
          System.out.println("List of Languages :");
          for(int i=0;i<size;i++)
          {
                   System.out.println(listArray[i]);
          }

}
}

Wrapper Classes
---------------------
Vectors cannot handle primitive data types like int,float,long,char, and double.
Primitive data types may be converted into object types by using the wrapper classes contained in the java.lang package.

Wrapper Classes for Converting Simple Types

Simple Type                                     Wrapper Class
boolean                                    Boolean
char                                         Character
double                                     Double
float                                         Float
int                                            Integer
long                                         Long


Converting Primitive Numbers to Object Numbers Using Constructor
----------------------------------------------------------------------------------
Methods
-----------
Constructor Calling                                    Conversion Action

Integer IntVal=new Integer(i);           Primitive Integer to Integer object
Float FloatVal=new Float(f)             Primitive Float to Float object
Double DoubleVal=new Double(d);  Primitive Double to Double object
Long LongVal=new Long(l);             Primitive long to Long object

Converting Object Numbers to Primitive Numbers Using typeValue()
----------------------------------------------------------------------------------
Method
----------
Method Calling                                                    Conversion Action

int i=IntVal.intValue();                     Object to primitive integer
float f=FloatVal.floatValue();           Object to primitive float
long l=LongVal.longValue();             Object to primitive long
double d=DoubleVal.doubleValue(); Object to primitive double

Converting Numbers to String Using toString() Method
-------------------------------------------------------------------
Method Calling                                 Conversion Action

str=Integer.toString(i);                     Primitive integer to string
str=Float.toString(f);                          Primitive float to string
str=Double.toString(d);                   Primitive double to string
str=Long.toString(l);                       Primitive long to string

Converting String Objects to Numberic Objects Using the Static Method
--------------------------------------------------------------------------------------ValueOf()
-------------
Method Calling                                           Conversion Action

DoubleVal=Double.valueOf(str);      Converts string to Double object
FloatVal=Float.valueOf(str);            Converts string to Float object
IntVal=Integer.valueOf(str);              Converts string to Integer object
Longval=Long.valueOf(str);              Converts string to Long object

Converting Numeric Strings to Primitive Numbers Using Parsing Methods
-----------------------------------------------------------------------------------------
Method Calling                                           Conversion Action

int i=Integer.parseInt(str);                 Converts string to primitive integer
long l=Long.parseLong(str);             Converts string to primitive long



The Enumeration Interface
------------------------------
The Enumeration interface defines the methods by which we can enumerate (obtain one at a time) the elements in a collection of objects.

Enumeration specifies the following two methods:
boolean hasMoreElements( )
Object nextElement( )
When implemented, hasMoreElements( ) must return true while there are still more elements to extract, and false when all the elements have been enumerated.

nextElement( ) returns the next object in the enumeration as a generic Object reference.

Hashtable
------------
package:

import java.util
Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, we specify an object that is used as a key, and the value that we want linked to that key.

The Hashtable constructors are shown here:
Hashtable( )
Hashtable(int size)
Hashtable(int size, float fillRatio)
Hashtable(Map m)

Method                                                       Description
void clear( )                                       Resets and empties the hash table.
Object clone( )                         Returns a duplicate of the invoking object.
Enumeration elements( )            Returns an enumeration of the values
contained in the hash table.

Object get(Object key) Returns the object that contains the value
associated with key. If key is not in the hash table, a null object is returned.

Enumeration keys( ) --Returns an enumeration of the keys contained in the hash table.

Object put(Object key, Object value) Inserts a key and a value into the hash
table. Returns null if key isn’t already in the hash table; returns the previous value associated with key if key is already in the hash table.

No comments:

Post a Comment