Text11 Arrays

download Text11 Arrays

of 27

Transcript of Text11 Arrays

  • 8/12/2019 Text11 Arrays

    1/27

    Chapter XI

    The Array Data Structure

    Chapter XI Topics

    11.1 Introduction to Data Structures

    11.2 One-Dimensional Array Definition

    11.3 Accessing Array Elements by Index

    11.4 Assigning andom Array !alues

    11." Array #rocessing $it% t%e Arrays &lass

    11.' Summary

    &%a(ter )I *%e Array Data Structure 1+,

  • 8/12/2019 Text11 Arrays

    2/27

    11.1 Introduction to Data Structures

    Early in the course you were introduced to simple data types, like int, float, char,double, and boolean. Each one of these data types can be used to create a variety

    of required variables. A simple data type variable is a location in memory thatstores a singlevalue that can be used by a computer program. Single values arepractical for loop counter variables, maximum number of grades, the height ofPikes Peak and the number of medals won by the United States at the lastlympics. !rograms that handle passenger airline reservations, student collegetranscripts, employee payroll records and hospital patient information, requiremassive data storage. Such ma"or storage requirements cannot be handledefficiently by thousands of simple data type variables, each storing a single value.#ou will need more sophisticated data types.

    $t can be argued that you have been storing multiple values inside ob"ects since the

    very beginning, and that is very true. %owever, the data stored inside the classesand ob"ects so far have been one or more simple data types. &here are manysituations where data needs to hold more than one value. Such a situation calls forusing a data structure. So what is a data structure' (ook at a building. )otethat it is made up of smaller structures like rooms, halls, stairways, etc. A room ismade up of walls, floors, ceilings, desks, chairs, etc.

    Another example can be found with animals. Animals are organisms made up oforgan systems. Each organ system is made up of organs. rgans are made up oftissues, and tissues are made up of cells. *e could continue and work down tothe molecular and atomic level, but for this analogy, assume that the cell is thesimplest, lowest level. &he whole point is that the structure, an organism in thiscase, is made up of other, smaller structures, until eventually you reach thesmallest component.

    &hese two examples are used to motivate the definition of a data structure. $ncomputer science it really is the same idea. &he only difference in structures is thenature of the smallest building block used to create the structure. $n an animalorganism it is a cell. $n a building it may be a brick or a plank and in a computerscience data structure it is a simple data type.

    First Data Structure Definition

    A data structure is a data ty(e $%ose com(onents aresmaller data structures andor sim(le data ty(es.

    #ou will note that it states First Data Structure Definition. &his definition is notquite finished. *e will revisit the data structure definition again and make somerevisions. &he complete, and more accurate, definition will only add unnecessary

    #age 11+ Ex(osure a/a 2+110 #reA#&S Edition +"-31-11

  • 8/12/2019 Text11 Arrays

    3/27

    complexity right now. +irst we need to spend some time with a variety of datastructure examples before it makes sense to become more precise. &his approachis quite similar to teaching somebody to play a new card game. $t "ust does notmake sense to explain all the more intricate details of the game when playing forthe first time. +requently, the best approach is to deal the cards and explain as yougo along. After several hands are dealt, it is easier to summarie a variety of rules.$n other words, let us deal some hands first and then we talk some more.

    So what is the bottom line essence of this data structure, right now at this earlystage' $t is simple. #ou no longer have a data type that stores a single value.#ou can store more than one value in a data type that is a data structure. !ut inother words, any data type that can store more than one value is a data structure.

    Data Structure Starting Point

    Any data ty(e t%at can store more t%an one /alue is a datastructure.

    Alright, we have a starting point. )ow we need to look and see what computerscience has to offer for us in the data structures department. Exactly, what typesof data structures exist and what can they do for us. #ou may have noticed thatthe title of this chapter talks about arrays, which is one kind of data structure. &heimportance of data structures is such that frequently one whole chapter is devotedto one data structure in many computer science text books. Since this is the veryfirst chapter about any kind of data structure, it will help to give a brief overviewof several different types of data structures.

    The Array Data Structure

    &he array is the first historical data structure. &his data structure became popularwith the introduction of the first commercially, wide-used programming language,FORTRAN. +&A), which means +mula &A)slator, was designed forthe scientific - number crunching - community. A data structure, like an array, was

    necessary for the storing of large quantities of numbers.

    *hat does an array bring to mind' %ow about an array of flowers or an array ofbooks, or an array of anything else' *e think of an array as having multiple items- not a single item - and an array has the same type of items. *e can have an arrayof integers, an array of real numbers, an array of characters, and an array ofstrings. An array can have any kind of element, as long as each element is the

    &%a(ter )I *%e Array Data Structure 111

  • 8/12/2019 Text11 Arrays

    4/27

    same data type. #ou will find the name vector used frequently for one-dimensionalarrays and matrix for two-dimensional arrays.

    First Array Definition

    An arrayis a data structure $it% one0 or more0 elementsof t%e same ty(e.

    A one-dimensional array is freuently also called a vector.A t$o-dimensional array is freuently also called a matrix.

    nce again you see thisfirst definition expression. &his is the same story as the

    data structure definition. All this business is tied together. /ore completedefinitions will come later when each data structure is explained in more detail.

    The ecord Data Structure

    &he business community was not very happy with the +&A) language andparticularly with the data structure limitation of having an array and nothing else.$n the business world, data is not of the same type. &his is lovely in science andmath where numbers rule the discipline, but in business it is another story.

    0ata storage in business requires storing names, addresses, birth dates, number ofdependents, social security numbers, credit cards numbers, flight numbers, yearsworked, pay rates, credit balance available, etc. etc. etc. ne solution was tocreate many different arrays. Each array specialied in one part of some businessrecord. &here was an array of names, an array of addresses, an array of pay ratesand so on, which were calledparallel arrays. &his worked, but it was tedious.

    A new programming language became popular, called 12( 31mmon2usiness riented (anguage4, which introduced the record data structure. *hatdoes the word record bring to mind' %ow about a student5s record, anemployee5s record, a patient5s record, a passenger5s record' Each one of these

    records has the common thread of multiple information fields that can be of manydifferent types. &his type of data structure is precisely what the business worldrequired. 12( became a highly successful language 3it helped that the0epartment of 0efense adopted the language4 and the record is now an integralpart of programming. $nitially, records only stored data of different types. vertime, records have evolved and now improved records store actions that processthe data inside the same data structure. #ou have seen this improved record

    #age 112 Ex(osure a/a 2+110 #reA#&S Edition +"-31-11

  • 8/12/2019 Text11 Arrays

    5/27

    structure already in 6ava as the class, which is the primary component of b"ectriented !rogramming.

    ecord Definition

    A record is a data structure $it% one0 or more0 elements0called fields0 of t%e same or different data ty(es.

    The Fi!e Data Structure

    !rogramming languages have a convenient data structure that facilitates thetransfer of data to and from external storage. &he array and record may be lovely

    to store a complex set of data in the memory of a computer, but this data oftenneeds to be used at some future date. &he data needs to be stored in somepermanent manner. &he file data structure provides this ability.

    Fi!e Definition

    A fi!e is an internal data structure - $it% an uns(ecifiednumber of elements of t%e same ty(e - assigned to anexternal file name. *%e file data structure allo$s transferof data bet$een internal and external storage.

    "ther Data Structures

    &he three data structures - array, record 3class now4 and file - introduced in thissection are built-in 6ava data types. &hese data types are ready to go and can beused with very little effort. Using built-in data structures is a good starting point inan introductory computer science course. &here are many other types of datastructures that the programmer can create for a wide variety of special purposes.&he study and practice of these special user-created data structures is a ma"orfocus of the second semester college-level computer science course. ne exampleof such a special data structure will be presented here, the stack.

    &%a(ter )I *%e Array Data Structure 113

  • 8/12/2019 Text11 Arrays

    6/27

    The Stac# Data Structure

    ne important data structure in computer science is the stack. &his data structure

    will be explained, and used, in considerable detail in the future. ight nowconsider the following stack definition.

    Stac# Definition

    A stac is a data structure $it% elements of t%e same ty(e.Data elements of t%e stac data structure can onlybe accessed stored or retrie/ed at one end of t%e stacin a $IF" 5ast In0 6irst Out manner.

    (et us go to a large home improvement store to create an analogy about this datastructure business. #ou walk through one isle to get a variety of bolts and nuts ofdifferent sies. All the hardware is neatly organied in separate containers that areclearly labeled. #ou might think that the isle containing all the screws, bolts, nutsand hooks is a large record of hardware data. &here is one organied isle for manydifferent types of hardware. #ou walk directly to a container that is marked withthe sie bolt that you need. After that you walk to another container that storesthe correct sied nut that you need. &his is random access. #ou can select toaccess any items in any random pattern.

    A little later you need to pick up a new lawnmower. All the new lawnmowers arestored in neat stacks, eight boxes high. &he particular lawnmower that you needhappens to be the third box from the bottom of one stack. $t is not possible foryou to access this lawnmower randomly or directly. &he stack only allows accessat the top. Store employees carefully remove one box at a time with a forkliftfrom the top of the stack, until your lawn mower can be accessed. &his is notrandom access. 0ata access to the lawnmowers or a computer science stack isonly possible at one end. +urthermore, the access is Last n! First Out3LFO".

    )ow why do you need to use a stack data structure in computer science' &his is a

    topic for later discussion. ight now you need to learn about arrays. &he forwardpeek to the stack was provided to make a relevant comparison of different dataaccess. $t was used strictly to help explain that the manner of data access isfundamental to a data structure7s definition.

    &he understanding and use of data structures is one of the most significantcomponents of successful programming. #ou will be using many data structures8both 6ava provided data structures, and user-created data structures.

    #age 114 Ex(osure a/a 2+110 #reA#&S Edition +"-31-11

  • 8/12/2019 Text11 Arrays

    7/27

    &he definition of a data structure, given at the beginning of this introduction -- andthis has been a long introduction -- will be repeated here. (ook at this shortsentence closely. &he definition is strictly limited to the storing of information.)othing is stated about how the information accessed.

    First Data Structure Definition

    A data structure is a data ty(e $%ose com(onents aresmaller data structures andor sim(le data ty(es.

    &his is precisely why this is calledFirst Data Structure Definition. &he definitionwas fine for the very first introduction of a data structure, but it is not complete.

    &here is more to the story. Something has to be mentioned about the manner inwhich data is accessed.

    (et us make an analogy with a car here. A car is a complex piece of machinerythat consists of many components. *e can somewhat think of a car as a datastructure with components like doors, lights, transmissions, radios, steeringwheels, etc.

    $t is not sufficient to define a car by specifying that the car has doors, lights, atransmission, a radio, a steering wheel, etc. &he access of these components is ama"or part of the overall definition or understanding of the car.

    0o the doors only open with a key, or does it have remote access, or perhaps acombination code that must be entered to unlock the doors' $s the transmissionautomatic, or manual, and if it is manual, how many gears are there and what is thepattern' +urthermore, is the transmission two-wheel drive or four-wheel drive'&he steering wheel controls the direction of the car, but is it direct access or is itindirect access with power steering'

    &hese are all questions that must be answered before somebody purchases a car.&he precise definition of a car cannot be summed up by its components. &hemanner in which the components are accessed or operate has to be part of acomplete definition.

    &he same is true with data structures. #es, we need to know how data is storedand what type of data can be stored. ne ma"or difference between an array and arecord is the fact that an array can only store data of the same type, while therecord can store data of many different types. &hat is great, but it is not sufficient.%ow do we access the data and what can be done to the data is another question'1onsider the following altered data structure definition.

    &%a(ter )I *%e Array Data Structure 11"

  • 8/12/2019 Text11 Arrays

    8/27

    Improved Data Structure Definition

    A data structure is a data ty(e $%ose com(onents aresmaller data structures andor sim(le data ty(es. *%e

    storing and retrie/al of t%e data elements is (erformed byaccessing met%ods t%at c%aracteri7e t%e data structure.

    All of a sudden the clean and simple data structure definition has become rathernasty looking. %opefully, it will not seem all that bad. &he first sentence is oldstuff. *e have been there before talking about data storage. &he second sentenceexplains that data has to be accessed and the manner in which data is accessed andprocessed defines the nature of the data structure.

    &he remainder of this chapter will concentrate completely on arrays or subscriptedvariables. &he long introduction was provided to get some basic feel about thenature of data structures. 0o not be concerned if you know little about arrays.&he purpose of this chapter is precisely to clarify the array data structure. ightnow it is hoped that you have some feel for data structures in general

    11.% "ne&Dimensiona! Array Definition

    *hat comes to mind when you think of an array' &here is an array of flowers,and you may also have an array of 2arbie dolls, or perhaps an arrayof kitchenpots and pans. $n each case the array has a dual meaning. #ou are talking aboutmore than one element. And you are also indicating that these elements are alike.&hey do not all need to be identical, but they are of an identical type. &he array offlowers may include many different flowers, but they are all flowers.

    $f we only consider data storage, the following array definition is quite adequate.

    &he definition explains that an array is a data structure, and it explains that themultiple elements of the array are fixed in number and they are of the same type.&his is the definition that was presented in the introduction, a few pages back.

    First Array Definition

    #age 11' Ex(osure a/a 2+110 #reA#&S Edition +"-31-11

  • 8/12/2019 Text11 Arrays

    9/27

    An array is a data structure $it% a fixed number of elementsof t%e same ty(e.

    0ata structures are more than a means to store data. &hat was the main pointmade in switching from the first data structure definition to the improved datastructure definition. &he way in which the stored data is accessed is part of thedata structure definition. &his really is the essence of ! encapsulation. Storeboth the data and the actions that access the data. &his means that the first arraydefinition is not complete. Some indication must be given about data access. 0onot get too excited because Array data access is quite simple.

    Improved Array Definition

    An array is a data structure $it% a fixed number of elementsof t%e same ty(e. E/ery element of t%e array can beaccessed directly.

    &he improved array definition indicates that arrays can be accessed directly. %owis this accomplished if there are many different values stored in the same data type'Arrays use some unique index or subscript to identify each element in the datastructure. &he indexing approach is all around us. Streets are arrays of homes. $t

    is not sufficient to state that you live on #ain $treet. #ou need something like%&'( #ain $treet. An airplane contains an array of seats, but flight '%) specifiesthe flight, not the location where you sit in the plane. A boarding pass will saysomething like Flight '%)! Row *)! $eat +. A similar system applies to a footballgame5s reserved seat. #our ticket specifies the stadium and date along with thelocation of the seat.

    Another way to explain this array indexing business is to consider an array of desksin a classroom, more commonly known as a seating chart. $magine that it is thefirst school day. Some teacher believes in assigned seats and also wants to beorganied. Each student is given an assigned seat number. &he teacher7s seating

    chart, forRoom J116below, is one example.

    81'9Ingrid

    81:9Darlene

    81;9lae

    8139?ic%elle

    8149emy

    81"9=aley

    &%a(ter )I *%e Array Data Structure 11:

  • 8/12/2019 Text11 Arrays

    10/27

    8+'9Diana

    8+:9essica

    8+;9Da/id

    8+,9Ant%ony

    81+9Alec

    8+19Isolde

    8+29o%n

    8+39

  • 8/12/2019 Text11 Arrays

    11/27

    int number; 1+;int number, 1+,

    System.out.(rintnumber+ F B BSystem.out.(rintnumber1 F B BSystem.out.(rintnumber2 F B BSystem.out.(rintnumber3 F B BSystem.out.(rintnumber4 F B BSystem.out.(rintnumber" F B BSystem.out.(rintnumber' F B BSystem.out.(rintnumber: F B BSystem.out.(rintnumber; F B BSystem.out.(rintnumber, F B B

    System.out.(rintlnG

    G

    !rogram ,ava%%()12ava, in +igure 99.:, does not appear very different from theprevious program. &he similarity with the previous program is by the fact that teninteger values are assigned to ten variables. &hen the program continues anddisplays each one of the ten values. %owever, there is something odd about theseten variables. &here is some strange looking operator in use with a set of squarebrackets. Additionally, it seems that every one of the ten variables is called list.

    #ou are actually looking at the declaration of an integer array. Specifically, this isa declaration for a single variable, called list, which can store ten integer variables./any streets have an array of homes. &he street has a single name, like #ain$treet or 3ing Road. A street can be considered an array of homes. Since thereis a single street name, it becomes necessary to give a label to each home thatidentifies the home. Each home has a street number. $n the case of the list array,each element of the array has an index, which is placed between brackets.

    Figure 11.% a/a11+2.@a/a *%is (rogram declares an array of 1+ int elements. Eac% array element /alue is indi/idually assigned and dis(layed. *%ere does not a((ear any real benefit from t%e from (rogram exam(le.

    (ublic class a/a11+2

    (ublic static /oid mainString args89

    System.out.(rintlnBa/a11+2CnBint list89 declares t%e array ob@ect identifierlist ne$ int81+9 allocates memory for 1+ array elementslist8+9 1++list819 1+1list829 1+2list839 1+3

    &%a(ter )I *%e Array Data Structure 11,

  • 8/12/2019 Text11 Arrays

    12/27

    list849 1+4list8"9 1+"list8'9 1+'list8:9 1+:list8;9 1+;list8,9 1+,System.out.(rintlist8+9 F B BSystem.out.(rintlist819 F B BSystem.out.(rintlist829 F B BSystem.out.(rintlist839 F B BSystem.out.(rintlist849 F B BSystem.out.(rintlist8"9 F B BSystem.out.(rintlist8'9 F B BSystem.out.(rintlist8:9 F B BSystem.out.(rintlist8;9 F B BSystem.out.(rintlist8,9 F B BSystem.out.(rintln

    GG

    +igure 99.; displays a segment of the previous program. (et us examine each oneof the program statements.

    Figure 11.'

    int list89 line 1list ne$ int81+9 line 2

    list8+9 1++ line 3list819 1+1 line 4list829 1+2 line "

    (ine 9 declares variable list to be an array of int values.

    (ine : allocates space with the new operator for ten int values in the list array.

    (ine ; assigns value %(( to the first list space. 0o not get confused, becauseaccess to array elements is done by using index .(0 for the first element. &his alsomeans that the index of the last element of an array is always one less than thenumber of elements in the array.

    !rogram ,ava%%()12ava, which used an array variable, did not seem to providemuch of an improvement to program ,ava%%(%12ava, which used ten variables.2oth programs appeared functional and they were both about the same length.)ow look at program ,ava%%(*12ava, in figure 99.

  • 8/12/2019 Text11 Arrays

    13/27

    Figure 11.* a/a11+3.@a/a *%e (re/ious (rogram $it% se(arate statements for eac% array member assignment and dis(lay is no$ re(laced $it% t$o loo(s. *%e loo( counter0 index0 is used to s(ecify eac% array element in an efficient manner.

    (ublic class a/a11+3

    (ublic static /oid mainString args89

    System.out.(rintlnBa/a11+3CnBint list89list ne$ int81+9

    for int index + index H, indexFFlist8index9 index F 1++

    for int index + index H, indexFFSystem.out.(rintlist8index9 F B B

    System.out.(rintlnG

    G

    Figure 11.* Continued

    +igure 99.= isolates how cleverly an array uses a loop structure. $n this examplethe loop repeats ten times. &he loop counter, called index, starts at ( and ends at

    4, which is the range of the list index values. !reviously, you saw statements, likelist.50 6 *((7but now in place of a fixed integer, an integer variable 3index4 isused to assign ten values to ten list locations.

    Figure 11.+

    for ,int index - / index 0-/ index223!ist4index5 - index 2 1/

    !rogram ,ava%%(512ava, in figure 99.>, repeats the looping access shown in theprevious program. &his time the array declaration is done in a single statementrather than the two statements used previously.

    Figure 11.6 a/a11+4.@a/a *%is (rogram is t%e same list array and t%e same list /alues as t%e (re/ious (rogram. *%is time note t%at t%e array declaration is accom(lis%ed $it% one statement.

    &%a(ter )I *%e Array Data Structure 121

  • 8/12/2019 Text11 Arrays

    14/27

    (ublic class a/a11+4

    (ublic static /oid mainString args89

    System.out.(rintlnBa/a11+4CnBint list89 ne$ int81+9

    for int index + index H, indexFFlist8index9 index F 1++

    for int index + index H, indexFFSystem.out.(rintlist8index9 F B B

    GG

    +igure 99.? pulls the array declarations from two previous programs. &he first

    example uses two statements. &he second example combines the two statementsinto one. &he one-statement approach is more commonly used.

    Figure 11.7

    +eclaring an array with two 8rogram statements

    int !ist4 5/!ist - ne8 int415/

    +eclaring an array with one 8rogram statement

    int !ist4 5 - ne8 int415/

    $t is not necessary to declare the sie of an array if an initializer list is used.!rogram ,ava%%('12ava, in figure 99.@, shows a set of integer values placedbetween braces. &his type of syntax tells the computer that list is an integer arraywith ten elements and it simultaneously assigns the ten provided values.

    Figure 11.9 a/a11+".@a/a *%is (rogram demonstrates %o$ to initiali7e array elements. *%e Hne$ o(erator is not necessary in t%is case.

    (ublic class a/a11+"

    (ublic static /oid mainString args89

    System.out.(rintlnBa/a11+"CnBint list89 1++01+101+201+301+401+"01+'01+:Gfor int + H : FF

    System.out.(rintlnBlist8B F F B9 B F list89System.out.(rintln

    GG

    #age 122 Ex(osure a/a 2+110 #reA#&S Edition +"-31-11

  • 8/12/2019 Text11 Arrays

    15/27

    *hat you have seen so far is an integer array called list. Arrays are not limited tostoring integer values. +igure 99. repeats list as an integer array, continues withnames as a character array, and finishes with grades as a real number array.

    Figure 11.

    int list8 9 declares t%e array !istidentifierlist ne$ int81+9 allocates memory for 1+ int /ariables

    c%ar names8 9 declares t%e names array identifiernames ne$ c%ar82"9 allocates memory for 2" char/ariables

    double grades8 9 declares t%e grades array identifiergrades ne$ double8"+9 allocates memory for "+ dou)!e/ariables

    !rogram ,ava%%(12ava, in figure 99.9B, demonstrates that is no problem tocreate arrays with data values besides integers. &he same syntax is used forinitialier lists that contain characters and arrays. $t is important to realie thatcharacter values require singles quotes and string values require double quotes.

    Figure 11.1 a/a11+'.@a/a *%is (rogram demonstrates a c%aracter array and a string array. >ot% arrays use an initiali7er list.

    (ublic class a/a11+'

    (ublic static /oid mainString args89

    System.out.(rintlnBa/a11+'CnB

    c%ar list189 JAJ0J>J0J&J0JDJ0JEJ0J6J0J

  • 8/12/2019 Text11 Arrays

    16/27

    G

    11.* Assigning andom Array :a!ues

    %ard coding array elements during array definitions can be tedious. &his isespecially tedious if there are many arrays values. Entering array elements duringprogram execution also becomes quite annoying when there are many numbers tobe added. +requently, in the process of learning computer science it is importantto process a large quantity of data, and such data in many cases does not need tobe any specific values. $n other words, random data is "ust fine. &he only issue leftis the nature of the random data. Are integers, real numbers, characters or stringsrequired' $n this brief section you will learn how to assign a variety of data typesrandomly to an array.

    &he 9x8o class, introduced in 1hapter $C, provides a convenient random method.&his method requires two parameters. &he first parameter indicates the smallestpossible number generated for the random list and the second parameter indicatesthe largest possible number that will be generated by the method.

    !rogram ,ava%%(&12ava, in figure 99.99, demonstrates how to generate randomnumbers in a specified range, which is D9BB.. in this case, and assigns thesenumbers to a sequence of integer array elements. *hen you run this program, youmay not get the exact same set of numbers, but they will be in the same range from9BB to .

    Figure 11.11

    a/a11+:.@a/a *%is (rogram fills an integer array $it% a random set of numbers. *%e random numbers $ill be generated in t%e 81++..,,,9 range.

    Lote t%at a Bfixed loo(B is used for t%e data entry into t%e array as $ell as t%e dis(lay of t%e array elements.

    (ublic class a/a11+:

    (ublic static /oid mainString args89

    System.out.(rintlnBa/a11+:CnBint list89 ne$ int82+9for int + H 2+ FF

    list89 Ex(o.random1++0,,,for int + H 2+ FF

    #age 124 Ex(osure a/a 2+110 #reA#&S Edition +"-31-11

  • 8/12/2019 Text11 Arrays

    17/27

    System.out.(rintlnBlist8B F F B9 B F list89System.out.(rintln

    GG

    Figure 11.11 Continued

    !rogram ,ava%%(/12ava, in figure 99.9:, demonstrates the length keyword, whichhas nothing to do with randomness. (ength is too small a topic to devote an entiresection to it and length will be used frequently in future program examples.Arrays provide a convenient way to know how large an array is. $t is possible tokeep track of the sie of an array with a user-defined variable, but you can uselength at any time to determine the sie of the array. &he length keyword issomewhat of a strange creature. #ou may be tempted to use syntax likelist1length:", because the dot notation does give the impression that length is amethod of the listob"ect8 however, lengthis )& a method. length is actually afield similar to the ; field of the #ath class. Another similarity is that both

    length and ; are final variables or constants which means they cannot bechanged. #ou may notice the last line in the program tries to change the lengthfield. &he program compiles because that line is commented out. $f the commentsymbols were to be removed, the program would no longer compile.

    Figure 11.1% a/a11+;.@a/a *%is (rogram introduces t%e lengt% field to determine t%e number of elements in t%e array. emo/e t%e comments from line 1'

    &%a(ter )I *%e Array Data Structure 12"

  • 8/12/2019 Text11 Arrays

    18/27

    to obser/e $%at %a((ens $%en t%e lengt% field is altered.

    (ublic class a/a11+;

    (ublic static /oid mainString args89

    System.out.(rintlnBa/a11+;CnBString names89 BoeB0B*omB0BSueB0B?egBG

    int n names.lengt% data field access not a met%od call

    System.out.(rintlnB*%ere are B F n F B array elements.Bforint + H n FF

    System.out.(rintlnBnames8B F F B9 B F names89 names.lengt% 1+

    GG

    Figure 11.1% Continued

    andom strings are an interesting problem. &here are an incredible number ofpossible strings and a random string method would be very cumbersome, andactually totally unnecessary. An array of strings or an array of any conceivabledata type will still always use an integer value for the index. 1onsider the seatingchart, shown earlier, and imagine a teacher randomly generating numbers to call onstudents. As numbers pop up, the teacher treats each number as a reference orindex to a desk, looks at the seating chart, and then calls on the student by name.$t is also possible that the teacher keep the responsibility of knowing the index withthe student. A rude teacher might call on a student strictly by using the desknumber. At any rate you should be convinced that we can map a numerical value,which will be used to identify an array index, with the contents at that indexedlocation. &he contents can be anything, but the index will always be an integer in arange starting at ero and up to one less the number of elements in the array.

    !rogram ,ava%%(412ava, in figure 99.9;, constructs an array ob"ect with ten$trings. A random number between B and is assigned to the rndnt, which is

    used for the index. &his makes Frandom stringsG possible. #our display should besimilar to what is in the book. #our output will probably be in a different orderbecause we are working with random data.

    Figure 11.1'

    a/a11+,.@a/a *%is (rogram demonstrates %o$ to dis(lay an array of random strings.

    #age 12' Ex(osure a/a 2+110 #reA#&S Edition +"-31-11

  • 8/12/2019 Text11 Arrays

    19/27

    (ublic class a/a11+,

    (ublic static /oid mainString args89

    System.out.(rintlnBa/a11+,CnBint rndInt

    String names89 BAAB0B>>B0B&&B0BDDB0BEEB0B66B0B

  • 8/12/2019 Text11 Arrays

    20/27

    design and implement your own classes and methods. #ou will need to know bothhow to use existing tools and create your own tools.0ata structures require processing. Array processing includes element display,assigning values, sorting elements and searching elements. 6ava has veryconveniently provided us with an Arrays class, which can perform all these arrayprocessing needs.

    Disp!aying Array (!ements 8ith toString

    All the previous program examples required a loop structure to display arrayelements. #ou learned how to use a for loop to access, and display, arrayelements. %owever, a loop structure was required to visit the array elements. $nprogram ,ava%%%(12ava, in figure 99.9

  • 8/12/2019 Text11 Arrays

    21/27

    C!ass Arrays;

  • 8/12/2019 Text11 Arrays

    22/27

    C!ass Arrays; "7Arrays1fill:list5!@$A@"7

    Sorting Array (!ements 8ith sort

    Sorting is an extremely important array process. *hy exactly is sorting soimportant' 0o we like to see elements appear in sorted sequence' &he answer ismuch simpler. Sorting is important, because there is a need to search data. Everytime that a credit card is approved for a purchase, the credit card holder7sinformation must be found before approval is granted. 0oes the card exist' $s

    there sufficient credit left on the account for the purchase' &hese questions canonly be answered after performing a search, and searching is far more efficientwhen items are sorted. 6ust imagine finding somebody7s phone number in atelephone book where the names are not sorted.

    !rogram ,ava%%%)12ava, in figure 99.9>, demonstrates the sort method. +ourarrays are sorted in ascending order. +or characters and strings this means inalphabetical order. 0o keep in mind that sorting with characters and strings is

    #age 13+ Ex(osure a/a 2+110 #reA#&S Edition +"-31-11

  • 8/12/2019 Text11 Arrays

    23/27

    based on the numerical values of the characters. &his can have some interestingresults. (ower-case >a> has a larger numerical code than upper-case >B>, whichmeans that in a mixed upper"case#loer"case sorting environment, you will findthat the B will be placed before the a. )otice that the program output for list'does not appear correct. 1orrect sorting of strings requires that the strings are alllower-case or all upper-case.

    Figure 11.16

    a/a1112.@a/a *%is (rogram demonstrates t%e Hsort met%od of t%e HArrays class. ?et%od Hsort arranges array elements in ascending order.

    im(ort @a/a.util.Arrays necessary to use t%e HArrays class

    (ublic class a/a1112

    (ublic static /oid main String args89

    System.out.(rintlnBa/a1112CnBint list189 110,,0220;;0330::0440''0""Gdouble list289 1.102.203.304.40"."0'.'0:.:0;.;0,.,Gc%ar list389 JAJ0JIJ0J>J0J=J0J&J0J>B0B==B0B&&B0B

  • 8/12/2019 Text11 Arrays

    24/27

    String and character array e!ements are sorted in ascendingorder of the numerica! code va!ues. Incorrect processingmay occur if string va!ues are mixed upper&case and !o8er&case.

    int list%.0 6 >!>C>!>D>!>E>!>>!>+>!>F>!>9>=7

    Arrays1sort:list%"7Arrays1sort:list)"7Arrays1sort:list*"7

    Searching Array (!ements 8ith )inarySearch

    &he sort method does not give a clue how array elements are sorted. &he methodis simply called sort. n the other hand, the Arrays search method is calledbinary$earch, which is one specific searching process. #ou will fully appreciatethe mechanics of the binary search in the later algorithm chapter. ight now abrief explanation will help to clarify the name.

    &hink of the manner in which you search for a name in a telephone book. #ou

    know that the names are in alphabetical order. +ew people start at the first pageand steadily work forward. )o, you roughly split the book open at some estimatelocation and conclude that you need to move forward or backward. Each time anever smaller section is split again until the correct page is found.

    !rogram ,ava%%%*12ava, in figure 99.9?, demonstrates the binary$earch method.$t returns the index of the array element if the element value exists. A negativeindex value is returned if the element does not exist. emember that the firstelement in an array ob"ect starts with index ero.

    Figure 11.17

    a/a1113.@a/a *%is (rogram demonstrates t%e HbinarySearc% met%od of t%e HArrays class. ?et%od HbinarySearc% returns t%e index of a searc% element if it exists0 and returns a negati/e index /alue ot%er$ise.

    im(ort @a/a.util.Arrays necessary to use t%e HArrays class

    #age 132 Ex(osure a/a 2+110 #reA#&S Edition +"-31-11

  • 8/12/2019 Text11 Arrays

    25/27

    (ublic class a/a1113

    (ublic static /oid main String args89

    System.out.(rintlnBa/a1113CnBint list89 110,,0220;;0330::0440''0""GSystem.out.(rintlnArrays.toStringlist

    Arrays.sortlist

    System.out.(rintlnArrays.toStringlistSystem.out.(rintln

    System.out.(rintlnBIndex of 33 is B F Arrays.binarySearc%list033System.out.(rintlnBIndex of 11 is B F Arrays.binarySearc%list011System.out.(rintlnBIndex of ,, is B F Arrays.binarySearc%list0,,System.out.(rintlnBIndex of 1+ is B F Arrays.binarySearc%list01+System.out.(rintlnBCnCnB

    GG

    $t was mentioned earlier that the whole point in sorting is the ability to searchefficiently. $n the case of the binary search sorting is not simply a matter of

    efficiency8 it is a matter of accuracy. nce again you will appreciate this problembetter when you actually implement a binary search yourself. $t is easy to imaginethat an unsorted list causes problems. 1an you find a number in a phone bookwhen the names are not sorted' #ou make the assumptions to move forward orbackward in your search precisely because the phone book is alphabetied.

    !rogram ,ava%%%512ava, in figure 99.9@, attempts to perform various searches onlists that are not properly sorted. &he results are very inconclusive. $n many casesa negative index is returned, when in fact the array element does exist.

    Figure 11.19

    a/a1114.@a/a *%is (rogram demonstrates t%at an array must be sorted before t%e HbinarySearc% met%od is called. Erroneous indexes are returned if t%e list is not sorted.

    im(ort @a/a.util.Arrays necessary to use t%e HArrays class

    (ublic class a/a1114

    (ublic static /oid main String args89

    &%a(ter )I *%e Array Data Structure 133

  • 8/12/2019 Text11 Arrays

    26/27

    System.out.(rintlnBa/a1114CnBint list89 110,,0220;;0330::0440''0""GSystem.out.(rintlnArrays.toStringlistSystem.out.(rintlnSystem.out.(rintlnBIndex of 33 is B F Arrays.binarySearc%list033System.out.(rintlnBIndex of 11 is B F Arrays.binarySearc%list011System.out.(rintlnBIndex of ,, is B F Arrays.binarySearc%list0,,System.out.(rintlnBIndex of 1+ is B F Arrays.binarySearc%list01+

    System.out.(rintlnBCnCnBGG

    C!ass Arrays;

  • 8/12/2019 Text11 Arrays

    27/27

    generate random string values by using a random index of a string array to specifysome unknown string value.

    Arrays can be declared for one, two or more dimensions. Each dimension requiresits own index and access loop.

    Elements in an array are processed with four common algorithms. Elements aredisplayed, entered, sorted and searched. &here exist algorithms for each one ofthese processes. $n this chapter the Arrays class is used with methods to$tring,fill, sortand binary$earchto perform array processing. Using these methods isdone without knowledge of the algorithm implementation. &he implementation ofthese methods will be learned in a later chapter.