chapter 19 collection classes collections are classes
play

Chapter 19 Collection Classes Collections are classes designed - PDF document

Chapter 19 Collection Classes Collections are classes designed for holding groups of ob jects. Almost all non trivial programs need to main tain one or more collections of ob jects. Although the Ja v a library pro


  1. Chapter 19 Collection Classes Collections are classes designed for holding groups of ob jects. Almost all non trivial programs need to main tain one or more collections of ob jects. Although the Ja v a library pro vides only a few di�eren t forms of collection, the features pro vided b y these classes are v ery general, making them applicable to a wide v ariet y of problems. In this c hapter w e will �rst describ e some of the basic concepts common to the collection classes, then summarize the basic collections pro vided b y Ja v a, and �nally describ e a few con tainer t yp es that are not pro vided b y the standard library , but whic h can b e easily constructed b y the programmer. 19.1 Elemen ts T yp es and primitiv e v alue W rapp ers With the exception of the a rra y data t yp e, all the collections pro vided b y the Ja v a library main tain their v alues in v ariables of t yp e Object . There are t w o imp ortan t consequences of this feature: � Since primitiv e t yp es, suc h as in tegers, b o oleans, c haracters and �oating p oin t v alues, are not sub classes of Object , they cannot b e directly stored in these collections. � When v alues are remo v ed from the collection, they m ust b e cast bac k to their original t yp e. One w a y to circum v en t the �rst restriction is through the use of classes . A wr app er wrapp er class main tains a primitiv e data v alue, but is itself an ob ject, and can th us b e stored in a con tainer. Metho ds are t ypically pro vided to b oth to construct an instance of the wrapp er class from a primitiv e v alue, and to reco v er the original v alue from the wrapp er. The follo wing, for example, stores t w o in tegers in to instances of class Integer , then reco v ers the original v alues so that an arithmetic op eration can b e p erformed: 317

  2. 318 CHAPTER 19. COLLECTION CLASSES Integer wrapp er new Integer(int value) build Integer from int Integer(String value) parse in teger in String intV alue() v alue of Integer as int toString() return decimal string represen tation of Integer toBina ryString() return binary represen tation toOctalString() return o ctal represen tation toHexString() return hex represen tation Cha racter wrapp er new Cha racter(cha r value) con v ert cha r to Cha racter cha rV alue() return cha r v alue of Cha racter isLetter() determine if c haracter is letter isDigit() true if c haracter is digit Bo olean wrapp er new Bo olean (b o olean value) con v ert b o olean to Bo olean b o oleanV alue () retriev e b o olean v alue from Bo olean toString() generate string represen tation of b o olean Double wrapp er new Double(double) con v ert double to Double new Double(String) construct Double from string doubleV alue() return double v alue of Double Figure 19.1: W rapp er Classes and Selected Beha viors Integer a = new Integer(12); Integer b = new Integer(3); m ust reco v er the in t v alues to do arithmetic // int c = a.intValue() � b.intValue(); In addition, man y wrapp er classes pro vide other useful functionalit y , suc h as the abilit y to parse string v alues. A common w a y to con v ert a string con taining an in teger v alue literal in to an int , for example, is to use an Integer as a middle step: String text = "123"; // example string v alue Integer val = new Integer(text); // �rst con v ert to In teger int ival = val.intValue(); // then con v ert In teger to in t Figure 19.1 summarizes the most common wrapp er classes and a few of their more useful b eha viors.

  3. 19.2. ENUMERA TORS 319 19.2 En umerators All collections can b e en visioned as a linear sequence of elemen ts, ho w ev er the particular means used to access eac h elemen t di�ers from one collection t yp e to another. F or example, a v ector is indexed using an in teger p osition k ey , while a hash table can use an y t yp e of ob ject as a k ey . It is frequen tly desirable to abstract a w a y these di�erences, and access the elemen ts of the collection in sequence without regard to the tec hnique used to obtain the underlying v alues. This facilit y is pro vided b y the Enumeration in terface, and its v arious implemen tations. The Enumeration in terface sp eci�es t w o metho ds: hasMo reElements() A b o olean v alue that indicates whether or not there are an y more elemen ts to b e en umerated nextElement() Retriev es the next elemen t in the en umeration These t w o op erations are used together to form a lo op. The follo wing, for example, sho ws ho w all the elemen ts of a hash table could b e prin ted: f for (Enumeration e = htab.elements(); e.hasMoreElements () ; ) System.out.printl n (e.nextElement()) ; g The metho ds hasMo reElements() and nextElement should alw a ys b e in v ok ed in tandem. That is, nextElement should nev er b e in v ok ed unless hasMo reElements has �rst determined that there is another elemen t, and nextElement should nev er b e in v ok ed t wice without an in terv ening call on hasMo reElements . If it is necessary to refer more than once to the v alue returned b y nextElement , the result of the nextElement call should b e assigned to a lo cal v ariable: for (Enumeration e = htab.elements(); e.hasMoreElements () ; ) f Object value = e.nextElement(); if (value.equals(Te st) ) System.out.prin tln ("found object " + value); g With the exception of the arra y , all the collections pro vided b y the Ja v a library pro vide a function that generates an en umeration. In addition, sev eral other classes that are not necessarily collections also supp ort the en umeration proto col. F or example, a StringT ok enizer is used to extract w ords from a string v alue. The individual w ords are then accessed using en umeration metho ds. In Section 19.6.1 w e will describ e ho w the programmer can create a new t yp e of en umeration.

  4. 320 CHAPTER 19. COLLECTION CLASSES 19.3 The Arra y The most basic collection form in Ja v a is the arra y . As w e ha v e noted in earlier c hapters, the creation and manipulation of an arra y v alue is di�eren t in Ja v a than in man y other programming languages. The Ja v a language mak es a separation b et w een (a) declaring a v ariable of arra y t yp e, (b) de�ning the size of the arra y and allo cating space, and (c) assigning v alues to the arra y . In man y other languages the �rst and second tasks are merged together. Merging these concepts mak es it di�cult to, for example, write functions that will op erate on arra ys of an y size. These problems are largely eliminated in Ja v a's approac h to arra ys. An arra y v ariable is declared b y indicating the t yp e of elemen ts the arra y will con tain, and a pair of square brac k ets that indicate an arra y is b eing formed. The follo wing, for example, is from the solitaire game case study examined in Chapter 9. static public CardPile allPiles [ ]; The brac k ets can b e written either after the v ariable name, or after the t yp e. The follo wing, for example, is an equiv alen t declaration: static public CardPile [ ] allPiles; Note that the arra y is the only collection in the Ja v a library that requires the programmer to sp ecify the t yp e of elemen ts that will b e held b y the con tainer. An imp ortan t consequence of this is that the arra y is the only collection that can main tain non-ob ject t yp es, suc h as in tegers, b o oleans, or c haracters. Other con tainers hold their v alues as instances of class Object , and can therefore only hold primitiv e v alues if they are surrounded b y wrapp er classes ( Integer , Double , and so on). An arra y value is created, as are all v alues, using the new op erator. It is only when the arra y v alue is created that the size of the arra y is sp eci�ed. allPiles = new CardPile [ 13 ]; // create arra y of 13 card piles Arra ys can also b e created as an initialization expression in the original declaration. The initialization expression pro vides the v alues for the arra y , as w ell as indicating the n um b er of elemen ts. f 2, 19 g ; int primes [ ] = 3, 5, 7. 11, 13, 17, Elemen ts of an arra y are accessed using the subscript op erator. This is used b oth to retriev e the curren t v alue held at a giv en p osition, and to assign a p osition a new v alue: primes[3] = primes[2] + 2;

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend