1 Collections Working with More than One Number or Data Type or Object

Preview:

Citation preview

1

Collections

Working with More than One Number or Data Type or Object

2

Collections

There are three kinds of collections in Java:

• Arrays contain data types or objects

• Ordered Collections contain data types or objects (Vectors, LinkedLists ,ArrayList)

• Dictionaries (or maps- "hash tables" in Java) containing data types or objects

• All three collections are objects

3

Which Type of Collection Should We Use?

• Type depends on the nature of the problem• Key characteristics to determine which type of collection

to use:– Array: easy to create and use, but fixed size.– Sets: Set or SortedSet– Ordered Collection (or Lists -ArrayList): just about as easy to

create and use, and can grow and shrink. More flexible. Have Iterators.

– Linked Data Structures – true dynamic– Dictionary (or Map - Hashtable): used to store and retrieve

values based on a key. Fast and easy for this purpose. Can also enumerate keys and values.

4

Arrays• Can hold any data type or object• The size is fixed (!!) during declaration• For example:

– int [ ] daysInMonth;– String monthNames [ ];

• To initialize:– daysInMonth = new int [ 12 ];– monthNames = new String [ 12 ];

5

Arrays• Alternate array declaration:• For example:

– int [ ] daysInMonth;– String monthNames [ ] ;

• The choice of placing the brackets before or after is a matter of style

• Garside and James Gosling (author of Java) uses before

• Patrick Naughton (author of Java) uses after

6

Arrays• To populate (beginning at zero):

– int daysInMonth [ ] = new int [ 12 ]; – daysInMonth [ 0 ] = 31;– daysInMonth [ 1 ] = 28;

• And:– String monthNames [ ] = new String [ 12 ]; – monthNames [ 0 ] = “January”;– monthNames [ 1 ] = “February”;

7

Arrays

• An alternate way to populate:– int [ ] daysInMonth = { 31, 28, 31, 30, 31, 30,

31, 31, 30, 31, 10, 31 };

• And:– String [ ] monthNames = { “January”;

“February”; “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December” };

8

Arrays

Other information:• Length is obtained from a public class

variable as follows:– int size1 = monthNames.length;– int size2 = daysInMonth.length;

• It is recommended that the programmer always used this class variable rather than a constant to make maintenance easier

9

Using Loops With Arrays

• int [ ] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 10, 31 };

• int sum = 0;

for (int ctr =0; ctr <= 11; ctr++)

{sum = sum + daysInMonth[ctr];}

10

Ordered Collections(for general info only)

• An Ordered Collection is similar to an array but it is more flexible– can grow and shrink– despite its name, an Ordered Collection does

not keep its elements in order

• In Java an Ordered Collection is called a Vector or LinkedList or ArrayList

11

Declaring and Initializing Ordered Collections

• Declaring a Vector or ArrayList:– Vector orderedCollection;– ArrayList listOfCustomers;

• And initializing it:– orderedCollection = new Vector ( );– Could say: Collection myCollection;

12

Declaring and Initializing Ordered Collections

(note: this is for Vector or LinkedList)

• To add to ordered collection:– String thisCarType = new String("Toyota");– orderedCollection.add(thisCarType);

• To retrieve from the ordered collection:String car = (String) orderedCollection.get(0);

Note Cast – since get(int index) retrieves Object type

13

Ordered Collections• To locate in collection:

– String string = new String("Toyota"); – if (orderedCollection.contains (string) )

int index = orderedCollection.indexOf ( string);

• To find the size of a collection use:– int size = orderedCollection.size ( );

• Remember a Collection may grow

14

ArrayList

• Java 2 created a new group of Collections that have many more features than a simple Vector.

• An ArrayList is one example of these new super classes.

• An ArrayList has more behavior and is synchronized to permit multiprocessing

15

ArrayList

• For example to declare and initialize:– java.util.ArrayList cars = new java.util.ArrayList()

• To add to it:– cars.add ("Toyota");

• To get from it:– String string = (String) cars.get(0);

• To remove from it:– cars.remove(string);

• To get its size:– int size = cars.size();

16

ArrayListmethods are the same for LinkedList

• Java 2 collections use an iterator pattern instead of subscripts to iterate through a dictionaries values:

Iterator iterator = cars.iterator(); while(iterator.hasNext()) {

String car = (String)iterator.next(); System.out.println(“Car: " + car ); }

• Note that subscripts can still be used but seldom are.

17

Linked List• A linked list consists of a number of links, each of

which has a reference to the next link. • Adding and removing elements in the middle of a

linked list is efficient. • Visiting the elements of a linked list in sequential order

is efficient • Random access is not efficient

18

Inserting an Element into a Linked List is done by using a ListIterator

object for the LinkedList object

19

Java's LinkedList class

• Easy access to first and last elements with methods

o void addFirst(Object obj) o void addLast(Object obj)o Object getFirst() o Object getLast() o Object removeFirst() o Object removeLast()

20

ListIterator

• ListIterator object gives access to elements inside a LinkedList object

• ListIterator protects the linked list while giving access

• ListIterator encapsulates a position anywhere in the linked list

21

A ListIterator object in a LinkedList

List Iterator position

22

Conceptual View of the ListIterator

23

List Iterator

• The listIterator method of the LinkedList class gets a list iterator

LinkedList list = new LinkedList(); . . . ListIterator iterator = list.listIterator();

24

List Iterator

• The next method moves the iterator iterator.next();

• next throws a NoSuchElementException if

you are already past the end of the list

25

List Iterator

• hasNext returns true if there is a next element

if (iterator.hasNext())iterator.next();

26

List Iterator

• hasNext returns true if there is a next element

if (iterator.hasNext())iterator.next();

27

List Iterator

• The next method returns the object of the link that it is passing

while iterator.hasNext() {

Object obj = iterator.next(); //do something with the object

}

28

List Iterator

• To move the list position backwards, use: o hasPrevious o previous

29

Adding and Removing from a LinkedList

• The add method:

o Adds an object after the iterator

o Moves the iterator position past the new element

iterator.add("Juliet");

30

Adding and Removing from a LinkedList

• The remove method:

o Removes ando Returns the object that was

returned by the last call to next or previous

31

Efficiency of Operations for Arrays and List

32

A Queue

33

A Stack of Books

• A stack can be visualized as a stack of books.

• You place books on top and remove from the top.

34

Abstract Data Type Stack

• The Stack class is a concrete implementation of a stack in the Java library

• The Stack class uses an Object[] to implement a stack

……………………………………………

• OR you can just use the LinkedList class and only use the addLast() and removeLast() methods.

35

Dictionaries• In Java an Dictionary is called a Hashtable• For example to declare and initialize:

– Hashtable dictionary ;– Hashtable phoneBook;

• And initialize:– dictionary = new Hashtable ( );– phoneBook = new Hashtable ( );

• Note the parent class of Hashtable is Dictionary

36

Dictionaries• To add to a dictionary: SUE is the key

– dictionary.put ("Sue", "3249");

• To get from dictionary :– String string = (String) dictionary.get ("Sue");Note 1: what you store is what you retrieve. If you store a

car object, then you retrieve a car object, not a String, or an int, or a ...

Note 2: an object of type Object is returned, so you have to "cast" object to be stored in a String (or into whatever type of value was originally stored).

37

Dictionaries

• To find the size of a dictionary use:– int size = dictionary.size ( );

• To check if key is not there:String string = (String) dictionary.get ("Sue");

if (string = = null)

System.out.println ( "Not found: " + string);

• Remember a Dictionary may grow

38

Dictionaries• Sometimes we want to go through all the keys in

the dictionary– In the phone book example, this would be the list of

people's names

• Sometimes we want to go through all the values in the dictionary– In the phone book example, this would be a list of all

the phone numbers

• This is called "enumeration", and the list of keys (or values) is also called "an enumeration"

39

Dictionaries

• To enumerate through a dictionary's keys:Enumeration enumeration;

enumeration = dictionary.keys ( );

while(enumeration.hasMoreElements ( ) )

{

key = (String) enumeration.nextElement ( );

System.out.println ( "Key is: " + key);

}

40

Dictionaries• To enumerate through a dictionary's values:

Enumeration enumeration;enumeration = dictionary.elements ( ); while(enumeration.hasMoreElements ( ) ) { value = (String) enumeration.nextElement ( ); System.out.println ( "Value is: " + value); }

• Since you retrieve an object, you need to cast it back to the type of object it really is (e.g., a car)– you then pull out the values from the object using your getters

41

Which Type of Collection Should We Use?

• Type depends on the nature of the problem• Key characteristics to determine which type of

collection to use:– Array: easy to create and use, but fixed size.– Ordered Collection (or Vector): just about as easy to

create and use, and can grow and shrink. More flexible.

– Dictionary (or Hashtable): used to store and retrieve values based on a key. Fast and easy for this purpose. Can also enumerate keys and values.

Recommended