Arrays

Arrays
  • Used to handle sets of values of same type.
  • An array is an object that is a named set of variables of same type.
  • Each variable in the array is called an array element.
  • To refer to a particular element in an array, you may use the array name combined with an integer value called an index.
  • We put the index in square brackets following Variable name example data[99].This refers to the element in data array at index 99.
  • The first element of an array has an index 0.Thus the second element of the array will be at index 1.Third at 2 and so on.
  • The index may not be an integer literal.It can be any expression that results in value of type int that is equal to or greater than zero.
Array Variables
  • The memory that is allocated for an array variable stores a reference to an array object,and not array.
  • The array object is a distinct entity that will be elsewhere in memory.
  • Variables that refer to objects store references that record the memory locations they refer to.
    • For Example :int[] primes;
    • This statement only declares a variable which will refer to the location that will hold an integer array.
    • Hence no memory is allocated as of now.
    • Above statement first word defines the type of array it will refer to,which in this case is int.
    • The square brackets define that it will be an array referencing an array of int values.
    • The third word is the variable name which in case is primes.
    • We can also use following notation : int primes[];
Defining an Array
    • Once an array is declared it is defined using : primes=new int[10];
      • This will create an array to store 10 int values and its reference will be stored in primes.
      • The new keyword is used to create a new object of array or allocating new memory for an object.
      • The array object is of type int and will have 10 elements.
      • Since each element is of type int and will require 4 bytes , the whole array will occupy 40 bytes plus 4 bytes of prime variable to store the reference to the array.
      • When an array is created all elements are initialized to a default value.
      • The initial value is "0" in case of an array of numerical values, is "false" for Boolean arrays,is "\u0000" for arrays storing type char and is "null" for an array of class type.
      • The index value of the above array is from 0-9.
    The length of an Array
    • Length of an array is referred to as number of elements it contains.
    • Length of an array is returned by "length" a data member of the array object.
    • "length" member can be used in for loop to iterate through elements of an array.
    • We can use short and byte as index values since their arithmetic produces a result of type "int".
    • An exception is thrown if we use the index less than 0 or greater than the index value for the last element in the array.
      • Exception type is "IndexOutOfBoundsException".
    • Arrays can be multidimensional depending upon the indexes they have.
    Reusing Array Variables
    • Since array variables refer to the location where array is stored they can be reused or updated with new array as per need.
      • So int[] primes = new int[10];
      • Now if we want to increase the size of an array we can simply write primes = new int[50].
      • This will discard the previous array and all its elements.
    • Though we can change array of an array variable.We cannot alter the type of an array to which variable refers.Thus prime can only refer to an integer array.
    Initialising Arrays
    • We can initialise arrays at the time of declaration as follows.
      • int[] primes={2,3,5,7,11,13,17};
    • We can also initialise manually later explicitly using
      • primes[0]=2;
      • primes[1]=3...
    • We can initialise using a for loop
      • for(int i=0;i<primes.length;i++)
      • {
      • primes[i]=1;
      • }
    Using a utility method to initialise an array

    • You can use a method that is defined in the Arrays class in java.util package to initialise an array. For example Arrays.fill(data,1.0);
      • fills all elements of data with 1.0.
      • name of array is passed as first argument which is "data" in this case.
      • need to import java.util.Arrays.
      • fill is a static method.
    Initialising and Array Variable
    • We can initialise an array variable with a reference to an existing array.
      • long[] even={22,42,62,8,102};
      • long[] value=even;
    • Both array variables refer to the same set of variables
      1:  import java.util.Arrays;  
      2:  /*  
      3:   * To change this license header, choose License Headers in Project Properties.  
      4:   * To change this template file, choose Tools | Templates  
      5:   * and open the template in the editor.  
      6:   */  
      7:  /**  
      8:   *  
      9:   * @author Gaurav Matta  
      10:   */  
      11:  public class ArrayInit {  
      12:    public void arrayRef()  
      13:    {  
      14:      int []arr1={1,2,3,4,5,6};  
      15:      int []arr2=arr1;  
      16:      Arrays.fill(arr1,9);  
      17:      for(int i=0;i<arr2.length;i++)  
      18:      {  
      19:        System.out.println(arr2[i]);  
      20:      }  
      21:    }  
      22:    public static void main(String args[])  
      23:    {  
      24:      //Both arrays refer to same array  
      25:      ArrayInit a1=new ArrayInit();  
      26:      a1.arrayRef();  
      27:    }  
      28:  }  
      

      Output:








      Using Arrays

      • To use arrays in expression to fill it with random values between 0.0 and 100.0 with following code.
        • double [] samples=new double[50];
        • for(int I=0;i<samples.length;i++)
        • {
        • samples[I]=100.0*Math.random();
        • }
      Using the collection Based for Loop with an Array

      • We can calculate average of numbers in an array using a collection based loop as follows
        • double average = 0.0;
        • for(double value:samples)
        • {
        • average+=value;
        • }
        • average/=samples.length;
      • When you want to process only data from a part of array we must use numerical for loop with loop counter ranging over the indexes for the elements you want to access.
      • Collection based for loop iterates over the values stored in an array.We cannot se the values in a collection based for loop.We use it when we want to access all the values in an array.
      • Lets look at an example.
      1:  import java.util.stream.IntStream;  
      2:  /*  
      3:   * To change this license header, choose License Headers in Project Properties.  
      4:   * To change this template file, choose Tools | Templates  
      5:   * and open the template in the editor.  
      6:   */  
      7:  /**  
      8:   *  
      9:   * @author Gaurav Matta  
      10:   */  
      11:  public class arrCricket   
      12:  {  
      13:    private static int runs=0;  
      14:    public String commentry()  
      15:    {  
      16:      String [][] comments=new String[5][];  
      17:      comments[0]=new String[]{  "Bowled Him That's a big wicket",  
      18:                    "That's in the air and Taken"};  
      19:  //    String [] wickets={"Bowled Him That's a big wicket","That's in the air and Taken"};  
      20:  //    comments[0]=wickets;  
      21:      return null;   
      22:    }  
      23:    public int score()  
      24:    {  
      25:      int run=(int)(6*Math.random());  
      26:      if(run==0)  
      27:      {  
      28:        System.out.println("You are Out!");  
      29:        run=0;  
      30:      }  
      31:      else if(run==1)  
      32:      {  
      33:        System.out.println("That's a quick single");  
      34:      }  
      35:      else if(run==2)  
      36:      {  
      37:        System.out.println("You looked for a double and got it");  
      38:      }  
      39:      else if(run==3)  
      40:      {  
      41:        System.out.println("Three more added to the total");  
      42:      }  
      43:      else if(run==4)  
      44:      {  
      45:        System.out.println("Brilliant Grounded Shot That's a four");  
      46:      }  
      47:      else if(run==5)  
      48:      {  
      49:        System.out.println("4 Wides that's what you not want any part of the Game");  
      50:      }  
      51:      else if(run==6)  
      52:      {  
      53:        System.out.println("That's Huge It's Out of Ground That's a six");  
      54:      }  
      55:      return run;  
      56:    }  
      57:    public static void main(String args[])  
      58:    {  
      59:      arrCricket ac=new arrCricket();  
      60:      String []players={"RG Sharma","S Dhawan","RR Pant","SK Raina","MK Pandey","KD Karthik","V Shankar","Washington Sundar","SN Thakur","JD Unadkat","YS Chahal"};  
      61:      int score[]=new int[players.length];  
      62:      int i=0;  
      63:      for(String player:players)  
      64:      {  
      65:        System.out.println(player+" walks in");  
      66:        int run=0;  
      67:        do  
      68:        {  
      69:          run=ac.score();  
      70:          runs=runs+run;  
      71:        }while(run!=0);  
      72:        score[i++]=runs;  
      73:        System.out.println(player+" scored "+runs);  
      74:        runs=0;  
      75:      }  
      76:      System.out.println("Scorecard Today");  
      77:      i=0;  
      78:      for(String player:players)  
      79:      {  
      80:        System.out.println(player+" "+score[i++]);  
      81:      }  
      82:      System.out.println("Total Score "+IntStream.of(score).sum());  
      83:    }  
      84:  }  
      Output :
      In above example we are using an array of players and while looping through them we are calculating their runs as we did earlier.

      Array of Arrays
      • These are arrays with multiple dimensions.
      • These are required when we want to capture many attributes of similar entities for example x & y are coordinates of different locations.
      • Suppose we have 10 locations and we ant to store their 2 coordinates we will have an array as follows.
        • float[][]locations=new float[10][2];
      • This is a 2 dimensional array since there are 2 dimensions one with indexes from 0-9 and other with indexes from 0 to 1.
      • Number of elements this array will have is 10X2 i.e 20 elements.
      Array of Arrays of Varing Length
        • An array of arrays can be of variable length.
        • For example following statement 
          • float[][]samples;
        • The variable can then be initialised on one dimension as
          • samples = new float[6][];
        • The sample variable can now reference to an array of any elements for example 6 and 101 in this case
          • samples[2]=new float[6];
          • samples[5]=new float[101];
        • The third element in array references to 6 elements of type float.
        • The sixth element of array references to an array of 101 elements of type float.
        • Each element of array takes 4 bytes so total size of an array with 21 elements will be 84 bytes.
        • We can loop through the array as follows 
          • for(int i=0;i<samples.length;i++)
          • {
          • for(j=0;j<samples[I].length;j++)
          • {
          • samples[i][j]=99.0f;
          • }
          • }
        Multidimensional Arrays
          • This limitation is not only limited to two but any number of indexes for example
            • long[][][][] pincodes=new long[5][10][2];
          • The array pincodes has 3 dimensions first it will store by country next it will store by states in a country and next it stores pinches of different states.
          • We can also initialise it as 
            • long[][][] pincodes=[5][6][5];
            • pincodes[0]=new long[4][];
            • pincodes[1]=new long[2][];
            • pincodes[2]=new long[5][];
          • So each array can hold independent one-dimensional array,  and you can also specify the sizes of these independently.
          Array of Characters
          • We can also define array of characters as follows
            • char[] message=new char[50];
          • Characters are stored as unicode in java so each element occupies 2 bytes.
          • We can preinitialise an array of characters at time of definition or initialise using an Arrays class function as follows
            • java.util.Arrays.fill(message,' ');
            • char[] vowels={'a','e','i','o','u'};
          1:  import java.io.BufferedReader;  
          2:  import java.io.IOException;  
          3:  import java.io.InputStreamReader;  
          4:  import java.net.HttpURLConnection;  
          5:  import java.net.URL;  
          6:  import java.util.Arrays;  
          7:  import java.util.List;  
          8:  import java.util.Random;  
          9:  import org.json.simple.JSONArray;  
          10:  import org.json.simple.JSONObject;  
          11:  import org.json.simple.parser.JSONParser;  
          12:  import org.json.simple.parser.ParseException;  
          13:  /*  
          14:   * To change this license header, choose License Headers in Project Properties.  
          15:   * To change this template file, choose Tools | Templates  
          16:   * and open the template in the editor.  
          17:   */  
          18:  /**  
          19:   *  
          20:   * @author Gaurav Matta  
          21:   */  
          22:  public class location {  
          23:    public static void main(String args[])  
          24:    {  
          25:      int latMin=-85;  
          26:      int latmax=85;  
          27:      int longMin=-180;  
          28:      int longmax=180;  
          29:      int [][] locations=new int [50][2];  
          30:      String [][][] vistor_list=new String [locations.length][locations.length][locations.length];  
          31:      String [] country = new String[locations.length];  
          32:      String [] adminsitrative_area1 = new String [locations.length];  
          33:      int nextCountryindex=0;  
          34:      int nextaal1index=1;  
          35:      int countryIndex=0;  
          36:      Object admin_area_name=null;  
          37:      for (int[] location : locations) {  
          38:        Random r = new Random();  
          39:        int randLat=r.nextInt(latmax - latMin + 1) + latMin;  
          40:        int randLong=r.nextInt(longmax - longMin + 1) + longMin;  
          41:        location[0] = randLat;  
          42:        location[1] = randLong;  
          43:      }  
          44:      for(int i = 0; i<locations.length; i++)   
          45:      {  
          46:        int aa1Index=0;  
          47:  //      System.out.println("At Longitude and Latitude :");  
          48:  //      for(int j=0;j<locations[i].length;j++)  
          49:  //      {  
          50:  //        System.out.println(locations[i][j]);  
          51:  //      }  
          52:        try  
          53:        {  
          54:          URL url=new URL("https://maps.googleapis.com/maps/api/geocode/json?latlng="+locations[i][0]+","+locations[i][1]+"&key=AIzaSyDkUmLA-5-n5J2wE0QdrL9IQb5EFdon5qM");  
          55:          HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
          56:          conn.setRequestMethod("GET");  
          57:          conn.setRequestProperty("Accept", "application/json");  
          58:          if (conn.getResponseCode() != 200)  
          59:          {  
          60:            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());  
          61:          }  
          62:          StringBuilder str = new StringBuilder();  
          63:          BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));  
          64:          String output;  
          65:          while ((output = br.readLine()) != null)   
          66:          {  
          67:            str.append(output).append("\n");  
          68:          }  
          69:          conn.disconnect();  
          70:          String result;  
          71:          result=str.toString();  
          72:          JSONParser parser = new JSONParser();  
          73:          try  
          74:          {  
          75:            Object obj = parser.parse(result);  
          76:            JSONObject obj2 = (JSONObject)obj;  
          77:            JSONArray results=(JSONArray)obj2.get("results");  
          78:            if(!(results.isEmpty()))  
          79:            {  
          80:              JSONObject obj3=(JSONObject)results.get(0);  
          81:              JSONArray address_components=(JSONArray) obj3.get("address_components");  
          82:              if(!(address_components.isEmpty()))  
          83:              {  
          84:                for(Object obj4:address_components)  
          85:                {  
          86:                  JSONObject obj5=(JSONObject) obj4;  
          87:                  JSONArray types=(JSONArray)obj5.get("types");  
          88:                  if(types.contains("administrative_area_level_1"))  
          89:                  {  
          90:                    Object long_name=obj5.get("long_name");  
          91:                    List<String> list = Arrays.asList(adminsitrative_area1);  
          92:                    if(list.contains((String)long_name))  
          93:                    {  
          94:                      aa1Index=list.indexOf(long_name);  
          95:                    }  
          96:                    else  
          97:                    {  
          98:                      aa1Index=nextaal1index++;  
          99:                      adminsitrative_area1[aa1Index]=(String)long_name;  
          100:                    }  
          101:                  }  
          102:                  if(types.contains("country"))  
          103:                  {  
          104:                    Object long_name=obj5.get("long_name");  
          105:  //                  System.out.println("Country : "+long_name);  
          106:                    List<String> list = Arrays.asList(country);  
          107:                    if(list.contains((String)long_name))  
          108:                    {  
          109:                      countryIndex=list.indexOf(long_name);  
          110:                    }  
          111:                    else  
          112:                    {  
          113:                      countryIndex=nextCountryindex++;  
          114:                      country[countryIndex]=(String)long_name;  
          115:                    }  
          116:  //                 Object long_name=obj5.get("long_name");  
          117:  //                 System.out.println("You are in "+long_name);  
          118:                  }  
          119:                  if(types.contains("administrative_area_level_2"))  
          120:                  {  
          121:                    admin_area_name=obj5.get("long_name");  
          122:                  }  
          123:                }  
          124:                if(vistor_list[countryIndex][aa1Index]!=null)  
          125:                {  
          126:                  List<String> list = Arrays.asList(vistor_list[countryIndex][aa1Index]);  
          127:                  if(!list.contains((String)admin_area_name))  
          128:                  {  
          129:                    int index=list.size()-1;  
          130:                    if(admin_area_name!=null)  
          131:                    {  
          132:                      vistor_list[countryIndex][aa1Index][index]=(String)admin_area_name;  
          133:                    }  
          134:                  }  
          135:                }  
          136:                else  
          137:                {  
          138:                  if(admin_area_name!=null)  
          139:                  {  
          140:                    String [] myarea=new String[]{(String)admin_area_name};  
          141:                    vistor_list[countryIndex][aa1Index]=myarea;  
          142:                  }  
          143:                }  
          144:  //              if ((admin_area_name!=null) && !list.contains((String)admin_area_name))  
          145:  //              {  
          146:  //                int index=list.size()-1;  
          147:  //                vistor_list[countryIndex][aa1Index][index]=(String)admin_area_name;  
          148:  //              }  
          149:              }  
          150:            }  
          151:            else  
          152:            {  
          153:  //            System.out.println("You are in Water");  
          154:            }  
          155:          }  
          156:          catch(ParseException e)  
          157:          {  
          158:            System.out.println("Error"+e);  
          159:          }  
          160:        }  
          161:        catch(IOException | RuntimeException e)  
          162:        {  
          163:          System.out.println("Error"+e);  
          164:        }  
          165:      }  
          166:      for(int i = 0; i<vistor_list.length; i++)  
          167:      {  
          168:        if(country[i]!=null)  
          169:        {  
          170:  //        System.out.println("Searching in Country : "+country[i]);  
          171:  //        System.out.println("============================================");  
          172:        }  
          173:        else  
          174:        {  
          175:          continue;  
          176:        }  
          177:        for(int j=0;j<vistor_list[i].length;j++)  
          178:        {  
          179:          if(adminsitrative_area1[j]!=null)  
          180:          {  
          181:  //          System.out.println("Searching in Area : "+adminsitrative_area1[j]);  
          182:  //          System.out.println("****************************************************");  
          183:          }  
          184:          else  
          185:          {  
          186:            continue;  
          187:          }  
          188:          for(int k=0;k<vistor_list[i][j].length;k++)  
          189:          {  
          190:            if(vistor_list[i][j][k]!=null)  
          191:            {  
          192:              System.out.println("--------------Found Location ::-------------");  
          193:              System.out.println("Country : "+country[i]);  
          194:              System.out.println("Area : "+adminsitrative_area1[j]);  
          195:              System.out.println("Area 2: "+vistor_list[i][j][k]);  
          196:              System.out.println("--------------Found Location ::-------------");  
          197:            }  
          198:          }  
          199:        }  
          200:      }  
          201:    }  
          202:  }  
          
          Output:











          In the above example we have a 3 dimensional array which captures the country the state and administrative area of random coordinates.
          We are taking help of Maps Api and parsing the result obtained as JSON object for which we are using certain predefined classes such as Arrays,Lists and Json Parser classes.

          Array Functions
          • arrayCopy
            • copy data from one array to another
          • Class Java.util.arrays has many array operation functions such as
            • copying
            • sorting
            • searching
          Array Class Example
           package javaimplant.arrays;  
           public class JavaArrayDemo {  
                public static void main(String[] args) {  
                     int[] sourceArray= {1,2,3,4,5,6};  
                     int[] destinationArray=new int[3];  
                     System.arraycopy(sourceArray,3,destinationArray,0,2);  
                     for(int i:sourceArray)  
                     {  
                          System.out.println(i);  
                     }  
                     for(int j:destinationArray)  
                     {  
                          System.out.println(j);  
                     }  
                }  
           }  
          
          ssd

          No comments:

          Post a Comment