Collections

A collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. Typically, they represent data items that form a natural group, such as a student's group(a collection of students), a disk directory (a collection of files), a telephone directory (a mapping of names to phone numbers). The Java language has a sophisticated Collections Framework that allows to create and manage collections of objects of various types.

A collections framework is a unified architecture for representing and manipulating collections. The collections frameworks contain the following:

Arrays

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. 

Illustration of an array as 10 boxes numbered 0 through 9; an index of 0 indicates the first element in the array

An array of ten elements

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.

Creating  an Array

Two steps procedure

1)  declares a reference to array of integers

type array_name [];                                           //type is the datatype of the array.
type []  array_name;   

int[] anArray;          or    int anArray[];         

2) create array referenced by this variable (allocate memory)

array_name = new type[size];      

    anArray = new int[5];     // all elements have 0 value

The two step integrated:
int[] anArray =new  int[5];

initiation

int[] anArray ={8,12,56,43,8};

Access the Elements of an Array 

You access an array element by referring to the index number [0 .. n).

public class Arr {
    public static void main(String arg[]) {
        int[] anArray ={8,12,56,43,8};
        System.out.println("Element [3]: "+anArray[3]); // the fourth  element in the array
    }
}

variable length - public data member, gives the number of elements in the array

anArray.length

public class Arr {
    public static void main(String arg[]) {
        int[] anArray ={8,12,56,43,8};
        System.out.println("Element [last]: "+anArray[anArray.length-1]); // the last element in the array
    }
}

Change an Array Element

To change the value of a specific element, refer to the index number:

public class Arr {
    public static void main(String arg[]) {
        int[] anArray ={8,12,56,43,8};
        System.out.println("Element [3]: "+anArray[3]); // the fourth  element in the array
        anArray[3]=84;
        System.out.println("new value - Element [3]: "+anArray[3]); // the fourth  element in the array
    }
}

Multi-dimensional Arrays

In additions to one-dimensional arrays, you can create multi-dimensional arrays. To declare two-dimensional arrays, you need to specify multiple square brackets after the array name.

Syntax to declare a two dimensional array
type array_name[][] = new type[rows][cols];

e.g.,
int multidim[][] = new int[3][6];   // crreate an array with 3*6 = 18 zero elements

In a two-dimensional array,

   1. You need to allocate memory for only the first dimension.
   2. You can allocate the remaining dimensions separately.
   3. When you allocate memory to the second dimension, you can also allocate different number to each dimension.

e.g.,

new int[3][];  // three lines       
multidim[0] = new int[2];         // first line - 2 elements
multidim[1] = new int[4];         // second line -4 elements
multidim[1] = new int[3];         // third line -3 elements

public class Arr2 {
    public static void main(String[] args) {     // creating an Array with 2+4+3=9 elements with value 0
        int multidim[][] = new int[3][];  // three lines
        multidim[0] = new int[2];         // first line - 2 elements
        multidim[1] = new int[4];         // second line -4 elements
        multidim[1] = new int[3];         // third line -3 elements
    }
}

initiation

public class Arr2_2 {
    public static void main(String[] args) {     // creating an Array with 2+4+3=9 elements with value 0
        int multidim[][] = { {2,54}, {4,3,1,5},{34,12,4}};  //  // first line - 2 elements, second - 4, third - 3
    }
}        

variable length   

multidim.length - number of lines in the array
multidim[0].length  - number of elements in the first line in the array
multidim[i].length -  
number of elements in the line number i+1 in the array

Accessing Arrays

You need to access various elements of an array to assign, retrieve, and manipulate the values stored in the array.
Assigning values to the Elements of an Array

To access a specific array element:

   1. You need to specify the name of the array and the index number of the element.
   2. The index position of the first element in the array is 0.
   3. In multidimensional array you need to give an index for each dimension starting with index 0.
 

public class Arr3 {
    public static void main(String[] args) {     // creating an Array with 2+4+3=9 elements with value 0
        int multidim[][][] = { {{2,54}, {4,3,1,5}},{{34,12,4},{34,21},{1,9,5}}}; 
        System.out.println (multidim[0][0][1]);
    }
}   

ArrayIndexOutOfBoundsException

Traversing a one-dimensional array

    simple for loop

public class Array{ 
   public static void main(String a[]){ 
      int ar[] = {-3,4,-17,2,-1,8};
      for(int i =0; i< ar.length;i++){
           System.out.print("   "+ar[i]); 
      }
  
}
-3  4  -17  2   -1  8

    for-each loop

for (<type>  <variable_name> : <collection>)
{

        // for body
}

The for-each loop is used to traverse arrays or other collections in Java. It is easier to use than a simple "for loop" because we don't need to increment the value and use subscript notation.

public class Array{ 
   public static void main(String a[]){ 
      int ar[] = {-3,4,-17,2,-1,8};
      for(int el :ar){
           System.out.println("   "+el); 
      }
  
}
-3  4  -17  2   -1  8

Traverse a bi-dimensional array 

    nested simple for loop

public class Array{ 
   public static void main(String a[]){ 
      int ar[][] = {{3,4},{17,2,1,8}}; 
      for(int i =0; i< ar.length;i++){ 
         for(int j = 0;j< ar[i].length; j++) System.out.print(" "+ar[i][j]); 
         System.out.println(); 
     
  
}
3 4 
17 2 1 8 

    for-each loop

public class Array{ 
   public static void main(String a[]){ 
      int ar[][] = {{3,4},{17,2,1,8}}; 
      for(int line[]:ar){ 
         for(int el:line) System.out.print(" "+el); 
         System.out.println(); 
     
  
}
3 4 
17 2 1 8 

Arrays from objects

The object's references are put in the array.  The constructors must be used to create the objects.


public class Array_s {
       public static void main(String a[]){
              String ar[][] = {{"Koko","Kiko","Kako"},{"Simo", "Sima"}};
              for(String[] line :ar){
                  for(String el:line)
                   System.out.print("   "+el);
                  System.out.println();
              }
           }
}
   Koko   Kiko   Kako
   Simo   Sima

 

Java array having instances of different classes (base and derived classes)

public class Person {
    String name;
    int age;
    Person(){      
        name = "Person"+ (int)(Math.random()*100);
        age = (int)(Math.random()*20)+10;
        System.out.println("Creating a person name = "+name+ " age "+ age);
    }
}
------------------------------------------------------------------------
public class Student extends Person{
    int javaNote;
    Student(){
        javaNote= (int)(Math.random()*5)+2;
        System.out.println("Student with java note: " + javaNote+"\n");
    }
    public String toString() {
        return "name: "+ name+"\tage:"+age+"\tjavaNote:"+javaNote;
    }
}
------------------------------------------------------------------------
public class Array_o {
    public static void main(String[] arg){
        Person [] arr;
        arr=new Person[10];     // creating an array with 10 null references
        for(int i=0;i<arr.length;i++){
            if(i%2 == 0)
                arr[i]= new Student();  // intiation with object from Student
            else
                arr[i]= new Person();   // intiation with object from Person
        }
    }
}
Creating a person name = Person78 age 26
Student with java note: 2

Creating a person name = Person88 age 21
Creating a person name = Person7 age 24
Student with java note: 6

Creating a person name = Person99 age 28
Creating a person name = Person33 age 24
Student with java note: 2

Creating a person name = Person89 age 25
Creating a person name = Person4 age 28
Student with java note: 5

Creating a person name = Person12 age 26
Creating a person name = Person35 age 17
Student with java note: 4

Creating a person name = Person15 age 28

arracopy() method -

The java.lang.System.arraycopy() method copies a source array elements from a specific beginning position to the destination array from the mentioned position. The number of elements to be copied are decided by len argument.

Syntax:
public static void arraycopy(source_arr, sourcePos,
dest_arr, destPos, len)
Parameters :
source_arr : array to be copied from
sourcePos : starting position in source array from where to copy
dest_arr : array to be copied in
destPos : starting position in destination array, where to copy in
len : total no. of components to be copied.

Return Value:

This method does not return any value.

Exception:

IndexOutOfBoundsException − if copying would cause access of data outside array bounds.
ArrayStoreException − if an element in the src array could not be stored into the dest array because of a type mismatch.
NullPointerException − if either src or dest is null.

Implementation

1) Elements from primitive types (byte, short, int, long,...)

public class CopyIntArr {
    public static void main(String arg[]) {
        int arrint[]= {4,3,45,2},arrint1[]=new int[4];
        for(int v:arrint) {
            System.out.print(v+"\t");
        }
        System.out.println();
        for(int v:arrint1) {
            System.out.print(v+"\t");
        }
        System.out.println("\n\n");
        //-----------------
        //System.arraycopy(src, srcPos, dest, destPos, length);
        System.arraycopy(arrint, 0, arrint1, 0, arrint.length);
       
        for(int v:arrint) {
            System.out.print(v+"\t");
        }
        System.out.println();
        for(int v:arrint1) {
            System.out.print(v+"\t");
        }
        System.out.println("\n\n");
        //--------------------------------
        arrint1[2]=125;      //changing a value
        for(int v:arrint) {
            System.out.print(v+"\t");
        }
        System.out.println();
        for(int v:arrint1) {
            System.out.print(v+"\t");
        }
        System.out.println("\n\n");
    }

}
      
4    3    45    2   
0    0    0    0   


4    3    45    2   
4    3    45    2   


4    3    45    2   
4    3    125    2


2) Elements - objects from classes

class Obj{
    int k;
    Obj(int p){
        k=p;
    }
    public String toString() {
        return k+"";
    }
    public void inc() {
        k++;
    }
}

public class CopyObjArr {
    public static void main(String arr[]) {
        Obj[] arrObj= {new Obj(4), new Obj(8),new Obj(14),new Obj(41)},
                  arrObj1=new Obj[4];
       
        for(Obj v:arrObj) {
            System.out.print(v+"\t");
        }
        System.out.println();
        for(Obj v:arrObj1) {
            System.out.print(v+"\t");
        }
        System.out.println("\n\n");
        //--------------------------------------------
        //System.arraycopy(src, srcPos, dest, destPos, length);
        System.arraycopy(arrObj, 0, arrObj1, 0, arrObj.length);
       
        for(Obj v:arrObj) {
            System.out.print(v+"\t");
        }
        System.out.println();
        for(Obj v:arrObj1) {
            System.out.print(v+"\t");
        }
        System.out.println("\n\n");
       
        //------------------------------------
        arrObj1[2].inc();
       
        for(Obj v:arrObj) {
            System.out.print(v+"\t");
        }
        System.out.println();
        for(Obj v:arrObj1) {
            System.out.print(v+"\t");
        }
        System.out.println("\n\n");             
    }
}
4    8    14    41   
null    null    null    null   


4    8    14    41   
4    8    14    41   


4    8    15    41   
4    8    15    41   


Attention: The method copies the references, so the references in both arrays point to the same objects in the system heap!