array

Document Sample
array Powered By Docstoc
					Classes - Intermediate
Chapter 4
Chapter 4


   4.0 Classes – Intermediate
     Method overloading

     Object as parameter

     Object as method type

     Array of objects

     Composite objects

     Application
    A problem with simple variables
3


       One variable holds one value
          The value may change over time, but at any given
           time, a variable holds a single value
       If you want to keep track of many values, you need
        many variables
       All of these variables need to have names
       What if you need to keep track of hundreds or
        thousands of values?
    Multiple values
4


       An array lets you associate one name with a fixed (but
        possibly large) number of values
       All values must have the same type
       The values are distinguished by a numerical index
        between 0 and [array size – 1]



                 0    1   2    3   4    5   6    7   8    9
    myArray 12 43         6   83 14 -57 109 12       0    6
    Indexing into arrays
5


       To reference a single array element, use
            array-name [ index ]
       Indexed elements can be used just like simple variables
          You can access their values

          You can modify their values

       An array index is sometimes called a subscript

                 0    1   2      3   4     5   6     7   8      9
     myArray 12 43        6     83 14 -57 109 12         0      6


    myArray[0]                myArray[5]           myArray[9]
    Using Array Elements
6


                 0   1   2    3   4   5   6    7   8   9
    myArray 12 43        6   83 14 -57 109 12      0   6

       Examples:
         x = myArray[1];       // sets x to 43
         myArray[4] = 99;             // replaces 14 with 99
         m = 5;
         y = myArray[m];       // sets y to -57
         z = myArray[myArray[9]];     // sets z to 109
    Strings and Arrays
7


       Strings and arrays both have special syntax
       Strings are objects, and can be used as objects
       Arrays are objects, but
         Arrays are created using special syntax:
          new type[size]          instead of new Person()
           If an array holds elements of type T, then the array’s
            type is ―array of T‖
    Array values
8


       An array may hold any type of value
       All values in an array must be the same type
         For example, you can have:
            an array of integers
            an array of Strings
            an array of Person
            an array of arrays of String
            an array of Object
                 In this case, all the elements are Objects; but they may
                  belong to different subclasses of Object
                 You probably want to cast the value to something more
                  specific after you get it from the array
    Declaration versus definition
9


       Arrays are objects
       Creating arrays is like creating other objects:
           the declaration provides type information and allocates
            space for a reference to the array (when it is created)
           the new definition actually allocates space for the array
           declaration and definition may be separate or combined
       Example for ordinary objects:
            Person p;                      // declaration
            p = new Person("John");        // definition
            Person p = new Person("John"); // combined
     Declaring and defining arrays
10


        Example for array objects:
            int myArray[ ];            // declaration
               This declares myArray to be an array of integers
               It does not create an array—it only provides a place to put an
                array
               Notice that the size is not part of the type

            myArray = new int[10]; // definition
               new int[10] creates the array
               The rest is an ordinary assignment statement

            int myArray[ ] = new int[10]; // both

                              0    1    2     3     4    5     6     7    8      9
myArray
                             0     0     0    0     0    0     0    0     0      0
     Arrays of Objects
11


        Actually, Arrays of Object References.
        Example: Box class
         Box[] ba; // Creates reference
         ba = new Box[10]; // Makes array object
        We now have 10 references which can refer to box objects!
         They will all be initialized to null.
        Constructions like this are allowed
         Box[] ba2={new Box(1,2), new Box(3,4), new Box(2,1)};
        It is very important to understand the necessity of creating
         new objects!
     Arrays of Objects
12                                                    ba
     Box[] ba = new Box[5];
     Box b = new Box(5,5);
     for(int i=0; i < ba.length; i++) {
         ba[i] = b;
                                               box l=5 w=5
     }


     Box[] ba2 = new Box[5];
     for(int i=0; i < ba2.length; i++) {              ba2
         ba2[i] = new Box(i+1,i+2);
     }

                          box l=1 w=2                   box l=5 w=6
                              box l=2 w=3        box l=4 w=5
     How many objects?
                                        box l=3 w=4
     An array’s size is not part of its type
13


        When you declare an array, you declare its type; you
         must not specify its size
          Example: String names[ ];

        When you define the array, you allocate space; you
         must specify its size
          Example: names = new String[50];

        This is true even when the two are combined
          Example: String names[ ] = new String[50];
     Alternate ways to declare arrays
14

        You can declare more than one variable in the same
         declaration:
             int a[ ], b, c[ ], d; // notice position of brackets
                a and c are int arrays
                b and d are just ints
        Another syntax:
             int [ ] a, b, c, d;          // notice position of brackets
                a, b, c and d are int arrays
          When the brackets come before the first variable, they
           apply to all variables in the list
        But...
          In Java, we typically declare each variable separately
     Array of Primitive :
     Array of Number Specifying Array Size during program
     execution
15


     int arraySize;

     System.out.Print(“Enter the size of array”)
     arraySize = console.nextInt();
     System.out.Println();

     int[] list =        new int[arraySize]


        Arrays that are instantiated during program execution
         are called dynamic array
     Array Initialization during Declaration
16


     double[] sales = {12.25, 32.50, 16.90, 23, 45.68};


        The values called initial values
                                     0      1     2      3     4
              sales
                                  12.25 32.50 16.90 23.00 45.68

        The size of the array is determined by the number of initial
         values within the braces.
        If an array is declared and initialized simultaneously, do not
         use the operator new to instantiate the array object
     Array assignment
17


        Array assignment is object assignment
        Object assignment does not copy values
           Person p1; Person p2;
           p1 = new Person("John");
           p2 = p1; // p1 and p2 refer to the same person
        Array assignment does not copy values
           int a1[ ]; int a2[ ];
           a1 = new int[10];
           a2 = a1; // a1 and a2 refer to the same array
     Array assignment
18


        When you assign an array value to an array variable, the
         types must be compatible
        The following is not legal:
           double dub[ ] = new int[10]; // illegal
        The following is legal:
           int myArray[ ] = new int[10];
          ...and later in the program,

           myArray = new int[500];      // legal!
          Legal because array size is not part of its type
     Instance Variable Length of an array
19


        Array is an object
        Every array has an instance variable, length, that tells how
         large the array is
        Example 1:
           int[ ] list = {10, 20, 30, 40, 50, 60};
          list.length is 6

        Example 2:
               int[] numList = new int[10];
            numlist.length is 10
     Example of array use I
20


        Suppose you want to find the largest value in an array scores
         of 10 integers:

           int largestScore = 0;
           for (int i = 0; i < 10; i++)
             if (scores[i] > largestScore)
                largestScore = scores[i];

        By the way, do you see an error in the above program?
          What if all values in the array are negative?
     Example of array use II
21


        To search the largest value in an array scores of 10 (possibly
         negative) integers:

           int largestScore = scores[0];
           for (int i = 1; i < 10; i++)
             if (scores[i] > largestScore)
                  largestScore = scores[i];
     Example of array use III
22

        Suppose you want to search the largest value in an array
         scores and the location in which you found it:

           int largestScore = scores[0];
           int index = 0;
           for (int i = 1; i < 10; i++) {
             if (scores[i] > largestScore) {
                 largestScore = scores[i];
                 index = i;
             }
           }
SEARCHING AND SORTING
     Searching
24


        Searching a list for a given item is one of the most common
         operations performed on a list. To search the list, you need:
          The list, that is, the array containing the list.

          The length of the list.

          The item for which you are searching.

          After the search is completed:

          If the item is found, then report ―success‖ and the location
           where the item was found.
          If the item is not found, then report ―failure.‖
     Linear search
25


        In a linear search, we start at the top of the list, and compare
         the element there with the key
        If we have a match, the search terminates and the index
         number is returned
        If not, we go on the the next element in the list
        If we reach the end of the list without finding a match, we
         return -1
     A linear search method
26

      public int search (String key) {
       int index = 0;
       boolean found = false;
       while (!found && index < list.size())
       {
          if (key.equals(list.get(index)))
               found = true;
          else
               index++;
       }
       if (found)
           return index;
       else
           return -1;
     }
         Bubble sort
27




        The basic idea is to compare two neighboring objects, and to
         swap them if they are in the wrong order.
        This is probably the simplest way to sort an array of objects.
        Unfortunately, it is also the slowest way!
     Bubble Sort (cont…)
28

        Compare each element (except the last one) with its neighbor to the
         right
           If they are out of order, swap them
           This puts the largest element at the very end
           The last element is now in the correct and final place

        Compare each element (except the last two) with its neighbor to the
         right
           If they are out of order, swap them
           This puts the second largest element next to last
           The last two elements are now in their correct and final places

        Compare each element (except the last three) with its neighbor to
         the right
           Continue as above until you have no unsorted elements on the
            left
     Example of Bubble Sort
29



      Compare
      and swap


        7 2 8 5 4   2 7 5 4 8   2 5 4 7 8   2 4 5 7 8
        2 7 8 5 4   2 7 5 4 8   2 5 4 7 8   2 4 5 7 8

        2 7 8 5 4   2 5 7 4 8   2 4 5 7 8     (done)
        2 7 5 8 4   2 5 4 7 8
        2 7 5 4 8
     Coding a bubblesort
30

     public static void bubbleSort(int list[ ], int listLength)
      {
        int counter, index;
        int temp;

         for (counter = 0; counter < listLength – 1; counter++)
         {
              for (index = 0; index < listLength–1-counter; index++)
                if (list[index] > list[index+1])
                {
                     temp = list[index];
                     list[index]= list[index+1];;
                      list[index+1]=temp;          }
              }
     }
     Sort
31


        http://www.cs.princeton.edu/courses/archive/fall04/cos2
         26/lectures/sort1.4up.pdf
        http://www.cs.ubc.ca/~harrison/Java/sorting-demo.html

				
DOCUMENT INFO
Categories:
Tags:
Stats:
views:8
posted:8/21/2011
language:English
pages:31