410 likes | 673 Views
Collections. Working with More than One Number or Data Type or Object. 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)
E N D
Collections Working with More than One Number or Data Type or Object
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
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.
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 ];
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
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”;
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” };
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
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];}
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
Declaring and Initializing Ordered Collections • Declaring a Vector or ArrayList: • Vector orderedCollection; • ArrayList listOfCustomers; • And initializing it: • orderedCollection = new Vector ( ); • Could say: Collection myCollection;
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
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
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
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();
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.
LinkedList • 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
Insertingan Element into a Linked List is done by using a ListIterator object for the LinkedList object
Java's LinkedList class • Easy access to first and last elements with methods • void addFirst(Object obj) • void addLast(Object obj) • Object getFirst() • Object getLast() • Object removeFirst() • Object removeLast()
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
A ListIterator object in a LinkedList List Iterator position
List Iterator • The listIterator method of the LinkedList class gets a list iterator LinkedList list = new LinkedList(); . . . ListIterator iterator = list.listIterator();
List Iterator • Thenextmethodmoves the iteratoriterator.next(); • nextthrowsa NoSuchElementException if you are already past the end of the list
List Iterator • hasNextreturns true if there is a next element if (iterator.hasNext()) iterator.next();
List Iterator • hasNextreturns true if there is a next element if (iterator.hasNext()) iterator.next();
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 }
List Iterator • To move the list position backwards, use: • hasPrevious • previous
Adding and Removing from a LinkedList • The add method: • Adds an object after the iterator • Moves the iterator position past the new element iterator.add("Juliet");
Adding and Removing from a LinkedList • The remove method: • Removes and • Returns the object that was returned by the last call to next or previous
A Stack of Books • A stack can be visualized as a stack of books. • You place books on top and remove from the top.
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.
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
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).
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
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"
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); }
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
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.