Size: px
Start display at page:

Download ""

Transcription

1 Generic Collections 16.1 Introduction 16.2 Collections Overview 16.3 Type-Wrapper Classes 16.4 Autoboxing and Auto-Unboxing 16.5 Interface Collection and Class Collections 16.6 Lists ArrayList and Iterator LinkedList 16.7 Collections Methods Method sort Method shuffle Methods reverse, fill, copy, max and min Method binarysearch Methods addall,frequency and disjoint 16.8 Stack Class of Package java.util 16.9 ClassPriorityQueue and Interface Queue Sets Maps Properties Class Synchronized Collections Unmodifiable Collections Abstract Implementations Wrap-Up Summary Self-Review Exercises Answers to Self-Review Exercises Exercises 16.1 Introduction In Section 7.16, we introduced the generic ArrayList collection a dynamically resizable array-like data structure that stores references to objects of a type that you specify when you create the ArrayList. In this chapter, we continue our discussion of the Java collections framework, which contains many other prebuilt generic data-structures. Some examples of collections are your favorite songs stored on your smartphone or media player, your contacts list, the cards you hold in a card game, the members of your favorite sports team and the courses you take at once in school. We discuss the collections-framework interfaces that declare the capabilities of each collection type, various classes that implement these interfaces, methods that process collection objects, and iterators that walk through collections. Java SE 8 After reading Chapter 17, Java SE 8 Lambdas and Streams, you ll be able to reimplement many of Chapter 16 s examples in a more concise and elegant manner, and in a way that makes them easier to parallelize to improve performance on today s multi-core systems. In Chapter 23, Concurrency, you ll learn how to improve performance on multi-core systems using Java s concurrent collections and parallel stream operations Collections Overview A collection is a data structure actually, an object that can hold references to other objects. Usually, collections contain references to objects of any type that has the is-a relationship with the type stored in the collection. The collections-framework interfaces declare the operations to be performed generically on various types of collections. Figure 16.1 lists some of the collections framework interfaces. Several implementations of these interfaces are provided within the framework. You may also provide your own implementations.

2 Interface Description Collection Set List Map Queue The root interface in the collections hierarchy from which interfaces Set, Queue and List are derived. A collection that does not contain duplicates. An ordered collection that can contain duplicate elements. A collection that associates keys to values and cannot contain duplicate keys. Map does not derive from Collection. Typically a first-in, first-out collection that models a waiting line; other orders can be specified. Fig Some collections-framework interfaces. Object-Based Collections The collections framework classes and interfaces are members of package java.util. In early Java versions, the collections framework classes stored and manipulated only Object references, enabling you to store any object in a collection, because all classes directly or indirectly derive from class Object. Programs normally need to process specific types of objects. As a result, the Object references obtained from a collection need to be downcast to an appropriate type to allow the program to process the objects correctly. As we discussed in Chapter 10, downcasting generally should be avoided. Generic Collections To elminate this problem, the collections framework was enhanced with the generics capabilities that we introduced with generic ArrayLists in Chapter 7 and that we discuss in more detail in Chapter 20, Generic Classes and Methods. Generics enable you to specify the exact type that will be stored in a collection and give you the benefits of compile-time type checking the compiler issues error messages if you use inappropriate types in your collections. Once you specify the type stored in a generic collection, any reference you retrieve from the collection will have that type. This eliminates the need for explicit type casts that can throw ClassCastExceptions if the referenced object is not of the appropriate type. In addition, the generic collections are backward compatible with Java code that was written before generics were introduced. Good Programming Practice 16.1 Avoid reinventing the wheel rather than building your own data structures, use the interfaces and collections from the Java collections framework, which have been carefully tested and tuned to meet most application requirements. Choosing a Collection The documentation for each collection discusses its memory requirements and its methods performance characteristics for operations such as adding and removing elements, searching for elements, sorting elements and more. Before choosing a collection, review the online documentation for the collection category you re considering (Set, List, Map, Queue, etc.), then choose the implementation that best meets your application s needs. Chapter 19, Searching, Sorting and Big O, discusses a means for describing how hard an

3 16.3 Type-Wrapper Classes algorithm works to perform its task based on the number of data items to be processed. After reading Chapter 19, you ll better understand each collection s performance characteristics as described in the online documentation Type-Wrapper Classes Each primitive type (listed in Appendix D) has a corresponding type-wrapper class (in package java.lang). These classes are called Boolean, Byte, Character, Double, Float, Integer, Long and Short. These enable you to manipulate primitive-type values as objects. This is important because the data structures that we reuse or develop in Chapters manipulate and share objects they cannot manipulate variables of primitive types. However, they can manipulate objects of the type-wrapper classes, because every class ultimately derives from Object. Each of the numeric type-wrapper classes Byte, Short, Integer, Long, Float and Double extends class Number. Also, the type-wrapper classes are final classes, so you cannot extend them. Primitive types do not have methods, so the methods related to a primitive type are located in the corresponding type-wrapper class (e.g., method parseint, which converts a String to an int value, is located in class Integer) Autoboxing and Auto-Unboxing Java provides boxing and unboxing conversions that automatically convert between primitive-type values and type-wrapper objects. A boxing conversion converts a value of a primitive type to an object of the corresponding type-wrapper class. An unboxing conversion converts an object of a type-wrapper class to a value of the corresponding primitive type. These conversions are performed automatically called autoboxing and auto-unboxing. Consider the following statements: Integer[] integerarray = new Integer[5]; // create integerarray integerarray[0] = 10; // assign Integer 10 to integerarray[0] int value = integerarray[0]; // get int value of Integer In this case, autoboxing occurs when assigning an int value (10) to integerarray[0], because integerarray stores references to Integer objects, not int values. Auto-unboxing occurs when assigning integerarray[0] to int variable value, because variable value stores an int value, not a reference to an Integer object. Boxing conversions also occur in conditions, which can evaluate to primitive boolean values or Boolean objects. Many of the examples in Chapters use these conversions to store primitive values in and retrieve them from data structures Interface Collection and Class Collections Interface Collection contains bulk operations (i.e., operations performed on an entire collection) for operations such as adding, clearing and comparing objects (or elements) in a collection. A Collection can also be converted to an array. In addition, interface Collection provides a method that returns an Iterator object, which allows a program to walk through the collection and remove elements from it during the iteration. We discuss class Iterator in Section Other methods of interface Collection enable a program to determine a collection s size and whether a collection is empty.

4 Chapter 16 Generic Collections Software Engineering Observation 16.1 Collection is used commonly as a parameter type in methods to allow polymorphic processing of all objects that implement interface Collection. Software Engineering Observation 16.2 Most collection implementations provide a constructor that takes a Collection argument, thereby allowing a new collection to be constructed containing the elements of the specified collection. Class Collections provides static methods that search, sort and perform other operations on collections. Section 16.7 discusses more about Collections methods. We also cover Collections wrapper methods that enable you to treat a collection as a synchronized collection (Section 16.13) or an unmodifiable collection (Section 16.14). Synchronized collections are for use with multithreading (discussed in Chapter 23), which enables programs to perform operations in parallel. When two or more threads of a program share a collection, problems might occur. As an analogy, consider a traffic intersection. If all cars were allowed to access the intersection at the same time, collisions might occur. For this reason, traffic lights are provided to control access to the intersection. Similarly, we can synchronize access to a collection to ensure that only one thread manipulates the collection at a time. The synchronization wrapper methods of class Collections return synchronized versions of collections that can be shared among threads in a program. Unmodifiable collections are useful when clients of a class need to view a collection s elements, but they should not be allowed to modify the collection by adding and removing elements Lists A List (sometimes called a sequence) is an ordered Collection that can contain duplicate elements. Like array indices, List indices are zero based (i.e., the first element s index is zero). In addition to the methods inherited from Collection, List provides methods for manipulating elements via their indices, manipulating a specified range of elements, searching for elements and obtaining a ListIterator to access the elements. Interface List is implemented by several classes, including ArrayList, LinkedList and Vector. Autoboxing occurs when you add primitive-type values to objects of these classes, because they store only references to objects. Classes ArrayList and Vector are resizable-array implementations of List. Inserting an element between existing elements of an ArrayList or Vector is an inefficient operation all elements after the new one must be moved out of the way, which could be an expensive operation in a collection with a large number of elements. A LinkedList enables efficient insertion (or removal) of elements in the middle of a collection, but is much less efficient than an ArrayList for jumping to a specific element in the collection. We discuss the architecture of linked lists in Chapter 21. ArrayList and Vector have nearly identical behaviors. Operations on Vectors are synchronized by default, whereas those on ArrayLists are not. Also, class Vector is from Java 1.0, before the collections framework was added to Java. As such, Vector has some methods that are not part of interface List and are not implemented in class ArrayList. For example, Vector methods addelement and add both append an element to a Vector, but only method add is specified in interface List and implemented by ArrayList. Unsynchro-

5 16.6 Lists nized collections provide better performance than synchronized ones. For this reason, Array- List is typically preferred over Vector in programs that do not share a collection among threads. Separately, the Java collections API provides synchronization wrappers (Section 16.13) that can be used to add synchronization to the unsynchronized collections, and several powerful synchronized collections are available in the Java concurrency APIs. Performance Tip 16.1 ArrayLists behave like Vectors without synchronization and therefore execute faster than Vectors, because ArrayLists do not have the overhead of thread synchronization. Software Engineering Observation 16.3 LinkedLists can be used to create stacks, queues and deques (double-ended queues, pronounced decks ). The collections framework provides implementations of some of these data structures. The following three subsections demonstrate the List and Collection capabilities. Section removes elements from an ArrayList with an Iterator. Section uses ListIterator and several List- and LinkedList-specific methods ArrayList and Iterator Figure 16.2 uses an ArrayList (introduced in Section 7.16) to demonstrate several capabilities of interface Collection. The program places two Color arrays in ArrayLists and uses an Iterator to remove elements in the second ArrayList collection from the first. 1 // Fig. 16.2: CollectionTest.java 2 // Collection interface demonstrated via an ArrayList object. 3 import java.util.list; 4 import java.util.arraylist; 5 import java.util.collection; 6 import java.util.iterator; 7 8 public class CollectionTest 9 { 10 public static void main(string[] args) 11 { 12 // add elements in colors array to list 13 String[] colors = {"MAGENTA", "RED", "WHITE", "BLUE", "CYAN"}; List<String> list = new ArrayList<String>(); for (String color : colors) list.add(color); // adds color to end of list // add elements in removecolors array to removelist 20 String[] removecolors = {"RED", "WHITE", "BLUE"}; List<String> removelist = new ArrayList<String>(); for (String color : removecolors) removelist.add(color); Fig Collection interface demonstrated via an ArrayList object. (Part 1 of 2.)

6 690 Chapter 16 Generic Collections 26 // output list contents 27 System.out.println("ArrayList: "); for (int count = 0; count < list.size() ; count++) 30 System.out.printf("%s ", list.get(count) ); // remove from list the colors contained in removelist 33 removecolors(list, removelist); // output list contents 36 System.out.printf("%n%nArrayList after calling removecolors:%n"); for (String color : list) 39 System.out.printf("%s ", color); 40 } // remove colors specified in collection2 from collection1 43 private static void removecolors( Collection<String> collection1, 44 Collection<String> collection2) 45 { 46 // get iterator Iterator<String> iterator = collection1.iterator(); // loop while collection has items 50 while ( iterator.hasnext() ) 51 { } 55 } 56 } // end class CollectionTest if (collection2.contains(iterator.next())) iterator.remove(); // remove current element ArrayList: MAGENTA RED WHITE BLUE CYAN ArrayList after calling removecolors: MAGENTA CYAN Fig Collection interface demonstrated via an ArrayList object. (Part 2 of 2.) Lines 13 and 20 declare and initialize String arrays colors and removecolors. Lines 14 and 21 create ArrayList<String> objects and assign their references to List<String> variables list and removelist, respectively. Recall that ArrayList is a generic class, so we can specify a type argument (String in this case) to indicate the type of the elements in each list. Because you specify the type to store in a collection at compile time, generic collections provide compile-time type safety that allows the compiler to catch attempts to use invalid types. For example, you cannot store Employees in a collection of Strings. Lines populate list with Strings stored in array colors, and lines populate removelist with Strings stored in array removecolors using List method add. Lines output each element of list. Line 29 calls List method size to get the number of elements in the ArrayList. Line 30 uses List method get to retrieve indi-

7 16.6 Lists 691 vidual element values. Lines also could have used the enhanced for statement (which we ll demonstrate with collections in other examples). Line 33 calls method removecolors (lines 43 55), passing list and removelist as arguments. Method removecolors deletes the Strings in removelist from the Strings in list. Lines print list s elements after removecolors completes its task. Method removecolors declares two Collection<String> parameters (lines 43 44) any two Collections containing Strings can be passed as arguments. The method accesses the elements of the first Collection (collection1) via an Iterator. Line 47 calls Collection method iterator to get an Iterator for the Collection. Interfaces Collection and Iterator are generic types. The loop-continuation condition (line 50) calls Iterator method hasnext to determine whether there are more elements to iterate through. Method hasnext returns true if another element exists and false otherwise. The if condition in line 52 calls Iterator method next to obtain a reference to the next element, then uses method contains of the second Collection (collection2) to determine whether collection2 contains the element returned by next. If so, line 53 calls Iterator method remove to remove the element from the Collection collection1. Common Programming Error 16.1 If a collection is modified by one of its methods after an iterator is created for that collection, the iterator immediately becomes invalid any operation performed with the iterator fails immediate and throws a ConcurrentModificationException. For this reason, iterators are said to be fail fast. Fail-fast iterators help ensure that a modifiable collection is not manipulated by two or more threads at the same time, which could corrupt the collection. In Chapter 23, Concurrency, you ll learn about concurrent collections (package java.util.concurrent) that can be safely manipulated by multiple concurrent threads. Software Engineering Observation 16.4 We refer to the ArrayLists in this example via List variables. This makes our code more flexible and easier to modify if we later determine that LinkedLists would be more appropriate, only the lines where we created the ArrayList objects (lines 14 and 21) need to be modified. In general, when you create a collection object, refer to that object with a variable of the corresponding collection interface type. Type Inference with the <> Notation Lines 14 and 21 specify the type stored in the ArrayList (that is, String) on the left and right sides of the initialization statements. Java SE 7 introduced type inferencing with the <> notation known as the diamond notation in statements that declare and create generic type variables and objects. For example, line 14 can be written as: List<String> list = new ArrayList<>(); In this case, Java uses the type in angle brackets on the left of the declaration (that is, String) as the type stored in the ArrayList created on the right side of the declaration. We ll use this syntax for the remaining examples in this chapter LinkedList Figure 16.3 demonstrates various operations on LinkedLists. The program creates two LinkedLists of Strings. The elements of one List are added to the other. Then all the Strings are converted to uppercase, and a range of elements is deleted.

8 692 Chapter 16 Generic Collections 1 // Fig. 16.3: ListTest.java 2 // Lists, LinkedLists and ListIterators. 3 import java.util.list; 4 import java.util.linkedlist; 5 import java.util.listiterator; 6 7 public class ListTest 8 { 9 public static void main(string[] args) 10 { 11 // add colors elements to list1 12 String[] colors = 13 {"black", "yellow", "green", "blue", "violet", "silver"}; 14 List<String> list1 = new LinkedList<>(); for (String color : colors) // add colors2 elements to list2 20 String[] colors2 = 21 {"gold", "white", "brown", "blue", "gray", "silver"}; 22 List<String> list2 = new LinkedList<>(); for (String color : colors2) list1.add(color); list2.add(color); list1.addall(list2); // concatenate lists 28 list2 = null; // release resources 29 printlist(list1); // print list1 elements converttouppercasestrings(list1); // convert to uppercase string 32 printlist(list1); // print list1 elements System.out.printf("%nDeleting elements 4 to 6..."); 35 removeitems(list1, 4, 7); // remove items 4-6 from list 36 printlist(list1); // print list1 elements 37 printreversedlist(list1); // print list in reverse order 38 } // output List contents 41 private static void printlist( List<String> list) 42 { 43 System.out.printf("%nlist:%n"); for (String color : list) 46 System.out.printf("%s ", color); System.out.println(); 49 } // locate String objects and convert to uppercase 52 private static void converttouppercasestrings( List<String> list) 53 { Fig Lists, LinkedLists and ListIterators. (Part 1 of 2.)

9 Lists ListIterator<String> iterator = list.listiterator(); while ( iterator.hasnext() ) 57 { String color = iterator.next(); // get item iterator.set(color.touppercase()); // convert to upper case } 61 } // obtain sublist and use clear method to delete sublist items 64 private static void removeitems( List<String> list, 65 int start, int end) 66 { } list.sublist(start, end).clear(); // remove items // print reversed list 71 private static void printreversedlist( List<String> list) 72 { 73 ListIterator<String> iterator = list.listiterator(list.size()); System.out.printf("%nReversed List:%n"); // print list in reverse order 78 while ( iterator.hasprevious() ) 79 System.out.printf("%s ", iterator.previous() ); 80 } 81 } // end class ListTest list: black yellow green blue violet silver gold white brown blue gray silver list: BLACK YELLOW GREEN BLUE VIOLET SILVER GOLD WHITE BROWN BLUE GRAY SILVER Deleting elements 4 to 6... list: BLACK YELLOW GREEN BLUE WHITE BROWN BLUE GRAY SILVER Reversed List: SILVER GRAY BLUE BROWN WHITE BLUE GREEN YELLOW BLACK Fig Lists, LinkedLists and ListIterators. (Part 2 of 2.) Lines 14 and 22 create LinkedLists list1 and list2 of type String. LinkedList is a generic class that has one type parameter for which we specify the type argument String in this example. Lines and call List method add to append elements from arrays colors and colors2 to the ends of list1 and list2, respectively. Line 27 calls List method addall to append all elements of list2 to the end of list1. Line 28 sets list2 to null, because list2 is no longer needed. Line 29 calls method printlist (lines 41 49) to output list1 s contents. Line 31 calls method converttouppercasestrings (lines 52 61) to convert each String element to uppercase, then line 32 calls printlist again to display the modified Strings. Line 35 calls method

10 694 Chapter 16 Generic Collections removeitems (lines 64 68) to remove the range of elements starting at index 4 up to, but not including, index 7 of the list. Line 37 calls method printreversedlist (lines 71 80) to print the list in reverse order. Method converttouppercasestrings Method converttouppercasestrings (lines 52 61) changes lowercase String elements in its List argument to uppercase Strings. Line 54 calls List method listiterator to get the List s bidirectional iterator (i.e., one that can traverse a List backward or forward). ListIterator is also a generic class. In this example, the ListIterator references String objects, because method listiterator is called on a List of Strings. Line 56 calls method hasnext to determine whether the List contains another element. Line 58 gets the next String in the List. Line 59 calls String method touppercase to get an uppercase version of the String and calls ListIterator method set to replace the current String to which iterator refers with the String returned by method touppercase. Like method touppercase, String method tolowercase returns a lowercase version of the String. Method removeitems Method removeitems (lines 64 68) removes a range of items from the list. Line 67 calls List method sublist to obtain a portion of the List (called a sublist). This is called a range-view method, which enables the program to view a portion of the list. The sublist is simply a view into the List on which sublist is called. Method sublist takes as arguments the beginning and ending index for the sublist. The ending index is not part of the range of the sublist. In this example, line 35 passes 4 for the beginning index and 7 for the ending index to sublist. The sublist returned is the set of elements with indices 4 through 6. Next, the program calls List method clear on the sublist to remove the elements of the sublist from the List. Any changes made to a sublist are also made to the original List. Method printreversedlist Method printreversedlist (lines 71 80) prints the list backward. Line 73 calls List method listiterator with the starting position as an argument (in our case, the last element in the list) to get a bidirectional iterator for the list. List method size returns the number of items in the List. The while condition (line 78) calls ListIterator s hasprevious method to determine whether there are more elements while traversing the list backward. Line 79 calls ListIterator s previous method to get the previous element from the list and outputs it to the standard output stream. Views into Collections and Arrays Method aslist Class Arrays provides static method aslist to view an array (sometimes called the backing array) as a List collection. A List view allows you to manipulate the array as if it were a list. This is useful for adding the elements in an array to a collection and for sorting array elements. The next example demonstrates how to create a LinkedList with a List view of an array, because we cannot pass the array to a LinkedList constructor. Sorting array elements with a List view is demonstrated in Fig Any modifications made through the List view change the array, and any modifications made to the array change the List view. The only operation permitted on the view returned by aslist is set, which changes the value of the view and the backing array. Any other attempts to change the view (such as adding or removing elements) result in an UnsupportedOperationException.

11 16.6 Lists 695 Viewing Arrays as Lists and Converting Lists to Arrays Figure 16.4 uses Arrays method aslist to view an array as a List and uses List method toarray to get an array from a LinkedList collection. The program calls method aslist to create a List view of an array, which is used to initialize a LinkedList object, then adds a series of Strings to the LinkedList and calls method toarray to obtain an array containing references to the Strings. 1 // Fig. 16.4: UsingToArray.java 2 // Viewing arrays as Lists and converting Lists to arrays. 3 import java.util.linkedlist; 4 import java.util.arrays; 5 6 public class UsingToArray 7 { 8 // creates a LinkedList, adds elements and converts to array 9 public static void main(string[] args) 10 { 11 String[] colors = {"black", "blue", "yellow"}; System.out.println("colors: "); for (String color : colors) 25 System.out.println(color); 26 } 27 } // end class UsingToArray LinkedList<String> links = new LinkedList<>(Arrays.asList(colors)); links.addlast("red"); // add as last item links.add("pink"); // add to the end links.add(3, "green"); // add at 3rd index links.addfirst("cyan"); // add as first item // get LinkedList elements as an array colors = links.toarray(new String[links.size()]); colors: cyan black blue yellow green red pink Fig Viewing arrays as Lists and converting Lists to arrays. Line 12 constructs a LinkedList of Strings containing the elements of array colors. Arrays method aslist returns a List view of the array, then uses that to initialize the LinkedList with its constructor that receives a Collection as an argument (a List is a Collection). Line 14 calls LinkedList method addlast to add "red" to the end of links. Lines call LinkedList method add to add "pink" as the last element and "green" as the element at index 3 (i.e., the fourth element). Method addlast (line 14) functions

12 696 Chapter 16 Generic Collections identically to method add (line 15). Line 17 calls LinkedList method addfirst to add "cyan" as the new first item in the LinkedList. The add operations are permitted because they operate on the LinkedList object, not the view returned by aslist. [Note: When "cyan" is added as the first element, "green" becomes the fifth element in the LinkedList.] Line 20 calls the List interface s toarray method to get a String array from links. The array is a copy of the list s elements modifying the array s contents does not modify the list. The array passed to method toarray is of the same type that you d like method toarray to return. If the number of elements in that array is greater than or equal to the number of elements in the LinkedList, toarray copies the list s elements into its array argument and returns that array. If the LinkedList has more elements than the number of elements in the array passed to toarray, toarray allocates a new array of the same type it receives as an argument, copies the list s elements into the new array and returns the new array. Common Programming Error 16.2 Passing an array that contains data to toarray can cause logic errors. If the number of elements in the array is smaller than the number of elements in the list on which toarray is called, a new array is allocated to store the list s elements without preserving the array argument s elements. If the number of elements in the array is greater than the number of elements in the list, the elements of the array (starting at index zero) are overwritten with the list s elements. Array elements that are not overwritten retain their values Collections Methods Class Collections provides several high-performance algorithms for manipulating collection elements. The algorithms (Fig. 16.5) are implemented as static methods. The methods sort, binarysearch, reverse, shuffle, fill and copy operate on Lists. Methods min, max, addall, frequency and disjoint operate on Collections. Method Description sort Sorts the elements of a List. binarysearch Locates an object in a List, using the high-performance binary search algorithm which we introduced in Section 7.15 and discuss in detail in Section reverse Reverses the elements of a List. shuffle Randomly orders a List s elements. fill Sets every List element to refer to a specified object. copy Copies references from one List into another. min Returns the smallest element in a Collection. max Returns the largest element in a Collection. addall Appends all elements in an array to a Collection. frequency Calculates how many collection elements are equal to the specified element. disjoint Determines whether two collections have no elements in common. Fig Collections methods.

13 Collections Methods 697 Software Engineering Observation 16.5 The collections framework methods are polymorphic. That is, each can operate on objects that implement specific interfaces, regardless of the underlying implementations Method sort Method sort sorts the elements of a List, which must implement the Comparable interface. The order is determined by the natural order of the elements type as implemented by a compareto method. For example, the natural order for numeric values is ascending order, and the natural order for Strings is based on their lexicographical ordering (Section 14.3). Method compareto is declared in interface Comparable and is sometimes called the natural comparison method. The sort call may specify as a second argument a Comparator object that determines an alternative ordering of the elements. Sorting in Ascending Order Figure 16.6 uses Collections method sort to order the elements of a List in ascending order (line 17). Method sort performs an iterative merge sort (we demonstrated a recursive merge sort in Section 19.8). Line 14 creates list as a List of Strings. Lines 15 and 18 each use an implicit call to the list s tostring method to output the list contents in the format shown in the output. 1 // Fig. 16.6: Sort1.java 2 // Collections method sort. 3 import java.util.list; 4 import java.util.arrays; 5 import java.util.collections; 6 7 public class Sort1 8 { 9 public static void main(string[] args) 10 { 11 String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"}; // Create and display a list containing the suits array elements 14 List<String> list = Arrays.asList(suits); 15 System.out.printf("Unsorted array elements: %s%n", list); Collections.sort(list); // sort ArrayList 18 System.out.printf("Sorted array elements: %s%n", list); 19 } 20 } // end class Sort1 Unsorted array elements: [Hearts, Diamonds, Clubs, Spades] Sorted array elements: [Clubs, Diamonds, Hearts, Spades] Fig Collections method sort. Sorting in Descending Order Figure 16.7 sorts the same list of strings used in Fig in descending order. The example introduces the Comparator interface, which is used for sorting a Collection s elements in

14 698 Chapter 16 Generic Collections a different order. Line 18 calls Collections s method sort to order the List in descending order. The static Collections method reverseorder returns a Comparator object that orders the collection s elements in reverse order. 1 // Fig. 16.7: Sort2.java 2 // Using a Comparator object with method sort. 3 import java.util.list; 4 import java.util.arrays; 5 import java.util.collections; 6 7 public class Sort2 8 { 9 public static void main(string[] args) 10 { 11 String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"}; // Create and display a list containing the suits array elements 14 List<String> list = Arrays.asList(suits); // create List 15 System.out.printf("Unsorted array elements: %s%n", list); // sort in descending order using a comparator Collections.sort(list, Collections.reverseOrder()); 19 System.out.printf("Sorted list elements: %s%n", list); 20 } 21 } // end class Sort2 Unsorted array elements: [Hearts, Diamonds, Clubs, Spades] Sorted list elements: [Spades, Hearts, Diamonds, Clubs] Fig Collections method sort with a Comparator object. Sorting with a Comparator Figure 16.8 creates a custom Comparator class, named TimeComparator, that implements interface Comparator to compare two Time2 objects. Class Time2, declared in Fig. 8.5, represents times with hours, minutes and seconds. 1 // Fig. 16.8: TimeComparator.java 2 // Custom Comparator class that compares two Time2 objects. 3 import java.util.comparator; 4 5 public class TimeComparator implements Comparator<Time2> 6 { 8 public int compare( Time2 time1, Time2 time2) 9 { 10 int hourdifference = time1.gethour() - time2.gethour(); if (hourdifference!= 0) // test the hour first 13 return hourcompare; Fig Custom Comparator class that compares two Time2 objects. (Part 1 of 2.)

15 16.7 Collections Methods int minutedifference = time1.getminute() - time2.getminute(); if (minutedifference!= 0) // then test the minute 18 return minutedifference; int seconddifference = time1.getsecond() - time2.getsecond(); 21 return seconddifference; 22 } 23 } // end class TimeComparator Fig Custom Comparator class that compares two Time2 objects. (Part 2 of 2.) Class TimeComparator implements interface Comparator, a generic type that takes one type argument (in this case Time2). A class that implements Comparator must declare a compare method that receives two arguments and returns a negative integer if the first argument is less than the second, 0 if the arguments are equal or a positive integer if the first argument is greater than the second. Method compare (lines 7 22) performs comparisons between Time2 objects. Line 10 calculates the difference between the hours of the two Time2 objects. If the hours are different (line 12), then we return this value. If this value is positive, then the first hour is greater than the second and the first time is greater than the second. If this value is negative, then the first hour is less than the second and the first time is less than the second. If this value is zero, the hours are the same and we must test the minutes (and maybe the seconds) to determine which time is greater. Figure 16.9 sorts a list using the custom Comparator class TimeComparator. Line 11 creates an ArrayList of Time2 objects. Recall that both ArrayList and List are generic types and accept a type argument that specifies the element type of the collection. Lines create five Time2 objects and add them to this list. Line 23 calls method sort, passing it an object of our TimeComparator class (Fig. 16.8). 1 // Fig. 16.9: Sort3.java 2 // Collections method sort with a custom Comparator object. 3 import java.util.list; 4 import java.util.arraylist; 5 import java.util.collections; 6 7 public class Sort3 8 { 9 public static void main(string[] args) 10 { 11 List<Time2> list = new ArrayList<>(); // create List list.add(new Time2(6, 24, 34)); 14 list.add(new Time2(18, 14, 58)); 15 list.add(new Time2(6, 05, 34)); 16 list.add(new Time2(12, 14, 58)); 17 list.add(new Time2(6, 24, 22)); 18 Fig Collections method sort with a custom Comparator object. (Part 1 of 2.)

16 700 Chapter 16 Generic Collections 19 // output List elements 20 System.out.printf("Unsorted array elements:%n%s%n", list); // sort in order using a comparator 23 Collections.sort(list, new TimeComparator()); // output List elements 26 System.out.printf("Sorted list elements:%n%s%n", list); 27 } 28 } // end class Sort3 Unsorted array elements: [6:24:34 AM, 6:14:58 PM, 6:05:34 AM, 12:14:58 PM, 6:24:22 AM] Sorted list elements: [6:05:34 AM, 6:24:22 AM, 6:24:34 AM, 12:14:58 PM, 6:14:58 PM] Fig Collections method sort with a custom Comparator object. (Part 2 of 2.) Method shuffle Method shuffle randomly orders a List s elements. Chapter 7 presented a card shuffling and dealing simulation that shuffled a deck of cards with a loop. Figure uses method shuffle to shuffle a deck of Card objects that might be used in a card-game simulator. 1 // Fig : DeckOfCards.java 2 // Card shuffling and dealing with Collections method shuffle. 3 import java.util.list; 4 import java.util.arrays; 5 import java.util.collections; 6 7 // class to represent a Card in a deck of cards 8 class Card 9 { 10 public static enum Face {Ace, Deuce, Three, Four, Five, Six, 11 Seven, Eight, Nine, Ten, Jack, Queen, King }; 12 public static enum Suit {Clubs, Diamonds, Hearts, Spades}; private final Face face; 15 private final Suit suit; // constructor 18 public Card(Face face, Suit suit) 19 { 20 this.face = face; 21 this.suit = suit; 22 } // return face of the card 25 public Face getface() 26 { Fig Card shuffling and dealing with Collections method shuffle. (Part 1 of 3.)

17 Collections Methods return face; 28 } // return suit of Card 31 public Suit getsuit() 32 { 33 return suit; 34 } // return String representation of Card 37 public String tostring() 38 { 39 return String.format("%s of %s", face, suit); 40 } 41 } // end class Card // class DeckOfCards declaration 44 public class DeckOfCards 45 { 46 private List<Card> list; // declare List that will store Cards // set up deck of Cards and shuffle 49 public DeckOfCards() 50 { 51 Card[] deck = new Card[52]; 52 int count = 0; // number of cards // populate deck with Card objects 55 for ( Card.Suit suit: Card.Suit.values()) 56 { 57 for ( Card.Face face: Card.Face.values()) 58 { 59 deck[count] = new Card(face, suit); 60 ++count; 61 } 62 } list = Arrays.asList(deck); // get List Collections.shuffle(list); // shuffle deck 66 } // end DeckOfCards constructor // output deck 69 public void printcards() 70 { 71 // display 52 cards in two columns 72 for (int i = 0; i < list.size(); i++) 73 System.out.printf("%-19s%s", list.get(i), 74 ((i + 1) % 4 == 0)? "%n" : ""); 75 } public static void main(string[] args) 78 { Fig Card shuffling and dealing with Collections method shuffle. (Part 2 of 3.)

18 702 Chapter 16 Generic Collections 79 DeckOfCards cards = new DeckOfCards(); 80 cards.printcards(); 81 } 82 } // end class DeckOfCards Deuce of Clubs Six of Spades Nine of Diamonds Ten of Hearts Three of Diamonds Five of Clubs Deuce of Diamonds Seven of Clubs Three of Spades Six of Diamonds King of Clubs Jack of Hearts Ten of Spades King of Diamonds Eight of Spades Six of Hearts Nine of Clubs Ten of Diamonds Eight of Diamonds Eight of Hearts Ten of Clubs Five of Hearts Ace of Clubs Deuce of Hearts Queen of Diamonds Ace of Diamonds Four of Clubs Nine of Hearts Ace of Spades Deuce of Spades Ace of Hearts Jack of Diamonds Seven of Diamonds Three of Hearts Four of Spades Four of Diamonds Seven of Spades King of Hearts Seven of Hearts Five of Diamonds Eight of Clubs Three of Clubs Queen of Clubs Queen of Spades Six of Clubs Nine of Spades Four of Hearts Jack of Clubs Five of Spades King of Spades Jack of Spades Queen of Hearts Fig Card shuffling and dealing with Collections method shuffle. (Part 3 of 3.) Class Card (lines 8 41) represents a card in a deck of cards. Each Card has a face and a suit. Lines declare two enum types Face and Suit which represent the face and the suit of the card, respectively. Method tostring (lines 37 40) returns a String containing the face and suit of the Card separated by the string " of ". When an enum constant is converted to a String, the constant s identifier is used as the String representation. Normally we would use all uppercase letters for enum constants. In this example, we chose to use capital letters for only the first letter of each enum constant because we want the card to be displayed with initial capital letters for the face and the suit (e.g., "Ace of Spades"). Lines populate the deck array with cards that have unique face and suit combinations. Both Face and Suit are public static enum types of class Card. To use these enum types outside of class Card, you must qualify each enum s type name with the name of the class in which it resides (i.e., Card) and a dot (.) separator. Hence, lines 55 and 57 use Card.Suit and Card.Face to declare the control variables of the for statements. Recall that method values of an enum type returns an array that contains all the constants of the enum type. Lines use enhanced for statements to construct 52 new Cards. The shuffling occurs in line 65, which calls static method shuffle of class Collections to shuffle the elements of the array. Method shuffle requires a List argument, so we must obtain a List view of the array before we can shuffle it. Line 64 invokes static method aslist of class Arrays to get a List view of the deck array. Method printcards (lines 69 75) displays the deck of cards in four columns. In each iteration of the loop, lines output a card left justified in a 19-character field followed by either a newline or an empty string based on the number of cards output so far. If the number of cards is divisible by 4, a newline is output; otherwise, the empty string is output Methods reverse, fill, copy, max and min Class Collections provides methods for reversing, filling and copying Lists. Collections method reverse reverses the order of the elements in a List, and method fill overwrites

19 16.7 Collections Methods 703 elements in a List with a specified value. The fill operation is useful for reinitializing a List. Method copy takes two arguments a destination List and a source List. Each source List element is copied to the destination List. The destination List must be at least as long as the source List; otherwise, an IndexOutOfBoundsException occurs. If the destination List is longer, the elements not overwritten are unchanged. Each method we ve seen so far operates on Lists. Methods min and max each operate on any Collection. Method min returns the smallest element in a Collection, and method max returns the largest element in a Collection. Both of these methods can be called with a Comparator object as a second argument to perform custom comparisons of objects, such as the TimeComparator in Fig Figure demonstrates methods reverse, fill, copy, max and min. 1 // Fig : Algorithms1.java 2 // Collections methods reverse, fill, copy, max and min. 3 import java.util.list; 4 import java.util.arrays; 5 import java.util.collections; 6 7 public class Algorithms1 8 { 9 public static void main(string[] args) 10 { 11 // create and display a List<Character> 12 Character[] letters = {'P', 'C', 'M'}; 13 List<Character> list = Arrays.asList(letters); // get List 14 System.out.println("list contains: "); 15 output(list); // reverse and display the List<Character> Collections.reverse(list); // reverse order the elements System.out.printf("%nAfter calling reverse, list contains:%n"); 20 output(list); // create copylist from an array of 3 Characters 23 Character[] letterscopy = new Character[3]; 24 List<Character> copylist = Arrays.asList(lettersCopy); // copy the contents of list into copylist Collections.copy(copyList, list); System.out.printf("%nAfter copying, copylist contains:%n"); 29 output(copylist); // fill list with Rs Collections.fill(list, 'R'); System.out.printf("%nAfter calling fill, list contains:%n"); 34 output(list); 35 } // output List information 38 private static void output(list<character> listref) 39 { Fig Collections methods reverse, fill, copy, max and min. (Part 1 of 2.)

20 704 Chapter 16 Generic Collections 40 System.out.print("The list is: "); for (Character element : listref) 43 System.out.printf("%s ", element); System.out.printf("%nMax: %s", Collections.max(listRef) ); 46 System.out.printf(" Min: %s%n", Collections.min(listRef) ); 47 } 48 } // end class Algorithms1 list contains: The list is: P C M Max: P Min: C After calling reverse, list contains: The list is: M C P Max: P Min: C After copying, copylist contains: The list is: M C P Max: P Min: C After calling fill, list contains: The list is: R R R Max: R Min: R Fig Collections methods reverse, fill, copy, max and min. (Part 2 of 2.) Line 13 creates List<Character> variable list and initializes it with a List view of the Character array letters. Lines output the current contents of the List. Line 18 calls Collections method reverse to reverse the order of list. Method reverse takes one List argument. Since list is a List view of array letters, the array s elements are now in reverse order. The reversed contents are output in lines Line 27 uses Collections method copy to copy list s elements into copylist. Changes to copylist do not change letters, because copylist is a separate List that s not a List view of the array letters. Method copy requires two List arguments the destination List and the source List. Line 32 calls Collections method fill to place the character 'R' in each list element. Because list is a List view of the array letters, this operation changes each element in letters to 'R'. Method fill requires a List for the first argument and an Object for the second argument in this case, the Object is the boxed version of the character 'R'. Lines call Collections methods max and min to find the largest and the smallest element of a Collection, respectively. Recall that interface List extends interface Collection, so a List is a Collection Method binarysearch The high-speed binary search algorithm which we discuss in detail in Section 19.4 is built into the Java collections framework as a static Collections method binarysearch. This method locates an object in a List (e.g., a LinkedList or an ArrayList). If the object is found, its index is returned. If the object is not found, binarysearch returns a negative

21 16.7 Collections Methods 705 value. Method binarysearch determines this negative value by first calculating the insertion point and making its sign negative. Then, binarysearch subtracts 1 from the insertion point to obtain the return value, which guarantees that method binarysearch returns positive numbers (>= 0) if and only if the object is found. If multiple elements in the list match the search key, there s no guarantee which one will be located first. Figure uses method binarysearch to search for a series of strings in an ArrayList. 1 // Fig : BinarySearchTest.java 2 // Collections method binarysearch. 3 import java.util.list; 4 import java.util.arrays; 5 import java.util.collections; 6 import java.util.arraylist; 7 8 public class BinarySearchTest 9 { 10 public static void main(string[] args) 11 { 12 // create an ArrayList<String> from the contents of colors array 13 String[] colors = {"red", "white", "blue", "black", "yellow", 14 "purple", "tan", "pink"}; 15 List<String> list = 16 new ArrayList<>(Arrays.asList(colors)); Collections.sort(list); // sort the ArrayList 19 System.out.printf("Sorted ArrayList: %s%n", list); // search list for various values 22 printsearchresults(list, "black"); // first item 23 printsearchresults(list, "red"); // middle item 24 printsearchresults(list, "pink"); // last item 25 printsearchresults(list, "aqua"); // below lowest 26 printsearchresults(list, "gray"); // does not exist 27 printsearchresults(list, "teal"); // does not exist 28 } // perform search and display result 31 private static void printsearchresults( 32 List<String> list, String key) 33 { 34 int result = 0; System.out.printf("%nSearching for: %s%n", key); if (result >= 0) result = Collections.binarySearch(list, key); 40 System.out.printf("Found at index %d%n", result); 41 else 42 System.out.printf("Not Found (%d)%n",result); 43 } 44 } // end class BinarySearchTest Fig Collections method binarysearch. (Part 1 of 2.)

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 36. Collections Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Introduction Arrays Class Interface Collection and Class Collections ArrayList Class Generics LinkedList Class Collections Algorithms

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Up to here Not included in program Java collections framework prebuilt data structures interfaces and methods for manipulating

More information

Java Collections Framework: Interfaces

Java Collections Framework: Interfaces Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection Interface The List Interface The Iterator Interface The ListIterator

More information

Generics. IRS W-9 Form

Generics. IRS W-9 Form Generics IRS W-9 Form Generics Generic class and methods. BNF notation Syntax Non-parametrized class: < class declaration > ::= "class" < identifier > ["extends" < type >] ["implements" < type list >]

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. Data structures Collections of related data items. Discussed in depth in Chapters 16 21. Array objects Data

More information

1. ArrayList and Iterator in Java

1. ArrayList and Iterator in Java 1. ArrayList and Iterator in Java Inserting elements between existing elements of an ArrayList or Vector is an inefficient operation- all element after the new one must be moved out of the way which could

More information

List... NOTE We use List as illustrative example of collections Study the others from textbook!

List... NOTE We use List as illustrative example of collections Study the others from textbook! List... NOTE We use List as illustrative example of collections Study the others from textbook! 25 What is a List? A List is an ordered Collection (sometimes called a sequence) Lists may contain duplicate

More information

The Java Collections Framework. Chapters 7.5

The Java Collections Framework. Chapters 7.5 The Java s Framework Chapters 7.5 Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework Outline Introduction to the Java s Framework Iterators Interfaces,

More information

Generic Collections CSC Spring 2019 Howard Rosenthal

Generic Collections CSC Spring 2019 Howard Rosenthal Generic Collections CSC 295-01 Spring 2019 Howard Rosenthal Course References Materials for this course have utilized materials in the following documents. Additional materials taken from web sites will

More information

Get started with the Java Collections Framework By Dan Becker

Get started with the Java Collections Framework By Dan Becker Get started with the Java Collections Framework By Dan Becker JavaWorld Nov 1, 1998 COMMENTS JDK 1.2 introduces a new framework for collections of objects, called the Java Collections Framework. "Oh no,"

More information

CS Ananda Gunawardena

CS Ananda Gunawardena CS 15-121 Ananda Gunawardena A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data,

More information

Java Collection Framework

Java Collection Framework Java Collection Framework Readings Purpose To provide a working knowledge of the Java Collections framework and iterators. Learning Objectives Understand the structure of the Java Collections framework

More information

Lecture 4. The Java Collections Framework

Lecture 4. The Java Collections Framework Lecture 4. The Java s Framework - 1 - Outline Introduction to the Java s Framework Iterators Interfaces, Classes and Classes of the Java s Framework - 2 - Learning Outcomes From this lecture you should

More information

9/16/2010 CS Ananda Gunawardena

9/16/2010 CS Ananda Gunawardena CS 15-121 Ananda Gunawardena A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data,

More information

Java Language Features

Java Language Features Java Language Features References: Object-Oriented Development Using Java, Xiaoping Jia Internet Course notes by E.Burris Computing Fundamentals with Java, by Rick Mercer Beginning Java Objects - From

More information

An Introduction to Data Structures

An Introduction to Data Structures An Introduction to Data Structures Advanced Programming ICOM 4015 Lecture 17 Reading: Java Concepts Chapter 20 Fall 2006 Adapded from Java Concepts Companion Slides 1 Chapter Goals To learn how to use

More information

Introduction to Computing II (ITI 1121) Final Examination

Introduction to Computing II (ITI 1121) Final Examination Université d Ottawa Faculté de génie École de science informatique et de génie électrique University of Ottawa Faculty of Engineering School of Electrical Engineering and Computer Science Introduction

More information

ArrayList. Introduction. java.util.arraylist

ArrayList. Introduction. java.util.arraylist ArrayList Introduction In this article from my free Java 8 course, I will be giving you a basic overview of the Java class java.util.arraylist. I will first explain the meaning of size and capacity of

More information

Lecture 6 Collections

Lecture 6 Collections Lecture 6 Collections Concept A collection is a data structure actually, an object to hold other objects, which let you store and organize objects in useful ways for efficient access Check out the java.util

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Opening Problem EXAMPLE. 1. Read one hundred numbers, 2. compute their average, and 3. find out how many numbers are above the average.

Opening Problem EXAMPLE. 1. Read one hundred numbers, 2. compute their average, and 3. find out how many numbers are above the average. Chapter 6 Arrays 1 Opening Problem EXAMPLE 1. Read one hundred numbers, 2. compute their average, and 3. find out how many numbers are above the average. 2 Introducing Arrays Array is a data structure

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss The Collections API Mark Allen Weiss Lecture Objectives To learn how to use the Collections package in Java 1.2. To illustrate features of Java that help (and hurt) the design of the Collections API. Tuesday,

More information

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.

More information

Java Collections Framework

Java Collections Framework Java Collections Framework Introduction In this article from my free Java 8 course, you will be given a high-level introduction of the Java Collections Framework (JCF). The term Collection has several

More information

CONTAİNERS COLLECTİONS

CONTAİNERS COLLECTİONS CONTAİNERS Some programs create too many objects and deal with them. In such a program, it is not feasible to declare a separate variable to hold reference to each of these objects. The proper way of keeping

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Section Lists and Sets

Section Lists and Sets Section 10.2 Lists and Sets IN THE PREVIOUS SECTION, we looked at the general properties of collection classes in Java. In this section, we look at some specific collection classes and how to use them.

More information

Highlights of Previous Lecture

Highlights of Previous Lecture Highlights of Previous Lecture Final Project Goals 1. Set up collections of Flights 2. Maintain information about reservation availability on flights 3. Respond to reservation requests 4. Set up collections

More information

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand COSC 236 Web Site You will always find the course material at: http://www.class-notes.us or http://www.class-notes.info or http://www.lecture-notes.tripod.com

More information

The Java Collections Framework and Lists in Java Parts 1 & 2

The Java Collections Framework and Lists in Java Parts 1 & 2 The Java Collections Framework and Lists in Java Parts 1 & 2 Chapter 9 Chapter 6 (6.1-6.2.2) CS 2334 University of Oklahoma Brian F. Veale Groups of Data Data are very important to Software Engineering

More information

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one Iterators What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one 9-2 2-2 What is an Iterator? An iterator is an abstract data

More information

What is the Java Collections Framework?

What is the Java Collections Framework? 1 of 13 What is the Java Collections Framework? To begin with, what is a collection?. I have a collection of comic books. In that collection, I have Tarzan comics, Phantom comics, Superman comics and several

More information

Homework 3. Due: Feb 25, 23:59pm. Section 1 (20 pts, 2 pts each) Multiple Choice Questions

Homework 3. Due: Feb 25, 23:59pm. Section 1 (20 pts, 2 pts each) Multiple Choice Questions Homework 3 Due: Feb 25, 23:59pm Section 1 (20 pts, 2 pts each) Multiple Choice Questions Q1: A function that modifies an array by using pointer arithmetic such as ++ptr to process every value of the array

More information

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline Java Intro 3 9/7/2007 1 Java Intro 3 Outline Java API Packages Access Rules, Class Visibility Strings as Objects Wrapper classes Static Attributes & Methods Hello World details 9/7/2007 2 Class Libraries

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba Laboratory Session: Exercises on classes Analogy to help you understand classes and their contents. Suppose you want to drive a car and make it go faster by pressing down

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

A variable is a name for a location in memory A variable must be declared

A variable is a name for a location in memory A variable must be declared Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;

More information

CS Programming I: ArrayList

CS Programming I: ArrayList CS 200 - Programming I: ArrayList Marc Renault Department of Computer Sciences University of Wisconsin Madison Spring 2018 TopHat Sec 3 (AM) Join Code: 427811 TopHat Sec 4 (PM) Join Code: 165455 ArrayLists

More information

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal The ArrayList class CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Describe the ArrayList class Discuss important methods of this class Describe how it can be used in modeling Much of the information

More information

Fundamental language mechanisms

Fundamental language mechanisms Java Fundamentals Fundamental language mechanisms The exception mechanism What are exceptions? Exceptions are exceptional events in the execution of a program Depending on how grave the event is, the program

More information

Announcements/Follow-ups

Announcements/Follow-ups Announcements/Follow-ups Midterm 2 graded Average was 52/80 (63%), Std. Dev. was 12 P5 and Lab8 P5 due tomorrow Very light Lab8 Practice with collections Due at end of lab period P6 posted tomorrow Due

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Java 1.8 Programming

Java 1.8 Programming One Introduction to Java 2 Usage of Java 3 Structure of Java 4 Flexibility of Java Programming 5 Two Running Java in Dos 6 Using the DOS Window 7 DOS Operating System Commands 8 Compiling and Executing

More information

Classes Classes 2 / 35

Classes Classes 2 / 35 Classes 1 / 35 Classes Classes 2 / 35 Anatomy of a Class By the end of next lecture, you ll understand everything in this class definition. package edu. gatech. cs1331. card ; import java. util. Arrays

More information

Today: Java Library Classes for lists. Iterators, ListIterators. CS61B Lecture #7. Last modified: Fri Sep 12 14:41: CS61B: Lecture #7 1

Today: Java Library Classes for lists. Iterators, ListIterators. CS61B Lecture #7. Last modified: Fri Sep 12 14:41: CS61B: Lecture #7 1 Today: Java Library Classes for lists. Iterators, ListIterators CS61B Lecture #7 Last modified: Fri Sep 12 14:41:31 2008 CS61B: Lecture #7 1 Abstracting Listness So far, we ve seen fairly primitive types

More information

+ Abstract Data Types

+ Abstract Data Types Linked Lists Abstract Data Types An Abstract Data Type (ADT) is: a set of values a set of operations Sounds familiar, right? I gave a similar definition for a data structure. Abstract Data Types Abstract

More information

Collections Questions

Collections Questions Collections Questions https://www.journaldev.com/1330/java-collections-interview-questions-and-answers https://www.baeldung.com/java-collections-interview-questions https://www.javatpoint.com/java-collections-interview-questions

More information

Java Programming with Eclipse

Java Programming with Eclipse One Introduction to Java 2 Usage of Java 3 Structure of Java 4 Flexibility of Java Programming 5 Using the Eclipse Software 6 Two Running Java in Eclipse 7 Introduction 8 Using Eclipse 9 Workspace Launcher

More information

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle Boggle If you are not familiar with the game Boggle, the game is played with 16 dice that have letters on all faces. The dice are randomly deposited into a four-by-four grid so that the players see the

More information

Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface

Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface Java Collections Framework Collection: a group of elements Based Design: Software 1 with Java Java Collections Framework s s Algorithms Recitation No. 6 (Collections) 2 Collection s Online Resources Collection

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

Strings and Arrays. Hendrik Speleers

Strings and Arrays. Hendrik Speleers Hendrik Speleers Overview Characters and strings String manipulation Formatting output Arrays One-dimensional Two-dimensional Container classes List: ArrayList and LinkedList Iterating over a list Characters

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

Software 1 with Java. Recitation No. 6 (Collections)

Software 1 with Java. Recitation No. 6 (Collections) Software 1 with Java Recitation No. 6 (Collections) Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework Interfaces Implementations Algorithms 2

More information

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321

Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double(3.14); 4... Zheng-Liang Lu Java Programming 290 / 321 Wrapper Classes To treat values as objects, Java supplies standard wrapper classes for each primitive type. For example, you can construct a wrapper object from a primitive value or from a string representation

More information

Relationship between Pointers and Arrays

Relationship between Pointers and Arrays Relationship between Pointers and Arrays Arrays and pointers are intimately related in C and often may be used interchangeably. An array name can be thought of as a constant pointer. Pointers can be used

More information

Timing for Interfaces and Abstract Classes

Timing for Interfaces and Abstract Classes Timing for Interfaces and Abstract Classes Consider using abstract classes if you want to: share code among several closely related classes declare non-static or non-final fields Consider using interfaces

More information

Object-Oriented Programming in the Java language

Object-Oriented Programming in the Java language Object-Oriented Programming in the Java language Part 6. Collections(1/2): Lists. Yevhen Berkunskyi, NUoS eugeny.berkunsky@gmail.com http://www.berkut.mk.ua Just before we start Generics Generics are a

More information

WA1278 Introduction to Java Using Eclipse

WA1278 Introduction to Java Using Eclipse Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 www.llcc.edu/cctc WA1278 Introduction to Java Using Eclipse This course introduces the Java

More information

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then 1 7 C Pointers 7.7 sizeof Operator 2 sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then int myarray[ 10 ]; printf( "%d", sizeof(

More information

Objects and Iterators

Objects and Iterators Objects and Iterators Can We Have Data Structures With Generic Types? What s in a Bag? All our implementations of collections so far allowed for one data type for the entire collection To accommodate a

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

Class 26: Linked Lists

Class 26: Linked Lists Introduction to Computation and Problem Solving Class 26: Linked Lists Prof. Steven R. Lerman and Dr. V. Judson Harward 2 The Java Collection Classes The java.util package contains implementations of many

More information

Programming for Engineers Pointers

Programming for Engineers Pointers Programming for Engineers Pointers ICEN 200 Spring 2018 Prof. Dola Saha 1 Pointers Pointers are variables whose values are memory addresses. A variable name directly references a value, and a pointer indirectly

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework SUMMARY COLLECTIONS FRAMEWORK PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2015 2016 Introduction Collections and

More information

Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING)

Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING) Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING) What is a Data Structure? Introduction A data structure is a particular way of organizing data using one or

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

Data Structures and Abstractions with Java

Data Structures and Abstractions with Java Global edition Data Structures and Abstractions with Java Fourth edition Frank M. Carrano Timothy M. Henry Data Structures and Abstractions with Java TM Fourth Edition Global Edition Frank M. Carrano University

More information

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

Chapter 6 - Pointers

Chapter 6 - Pointers Chapter 6 - Pointers Outline 1 Introduction 2 Pointer Variable Declarations and Initialization 3 Pointer Operators 4 Calling Functions by Reference 5 Using the const Qualifier with Pointers 6 Bubble Sort

More information

Algorithms. Produced by. Eamonn de Leastar

Algorithms. Produced by. Eamonn de Leastar Algorithms Produced by Eamonn de Leastar (edeleastar@wit.ie) Collections ± Collections Architecture ± Definition ± Architecture ± Interfaces ± Collection ± List ± Set ± Map ± Iterator ± Implementations

More information

Java Array List Interview Questions

Java Array List Interview Questions Java Array List Interview Questions codespaghetti.com/arraylist-interview-questions/ Array List Java Array List Interview Questions, Algorithms and Array List Programs. Table of Contents: CHAPTER 1: Top

More information

Arrays. Chapter Arrays What is an Array?

Arrays. Chapter Arrays What is an Array? Chapter 8 Arrays 81 Arrays 811 What is an Array? To motivate why we might be interested in using arrays, let us implement an app that creates a collection of doubles We will keep track of the number of

More information

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1 Topic #9: Collections CSE 413, Autumn 2004 Programming Languages http://www.cs.washington.edu/education/courses/413/04au/ If S is a subtype of T, what is S permitted to do with the methods of T? Typing

More information

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17 List of Programs xxv List of Figures xxix List of Tables xxxiii Preface to second version xxxv PART 1 Structured Programming 1 1 Getting started 3 1.1 Programming 3 1.2 Editing source code 5 Source code

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda

More information

CSE 143 Lecture 14. Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4

CSE 143 Lecture 14. Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4 CSE 143 Lecture 14 Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4 slides adapted from Marty Stepp and Hélène Martin http://www.cs.washington.edu/143/ Related classes Consider classes for

More information

Data Structures Java Collections Framework

Data Structures Java Collections Framework David Drohan Data Structures 04 - Java Collections Framework JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN 0132162709 2012 Pearson Education, Inc., Upper Saddle

More information

CSCE121: Introduction to Program Design and Concepts Practice Questions for Midterm 1

CSCE121: Introduction to Program Design and Concepts Practice Questions for Midterm 1 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING CSCE121: Introduction to Program Design and Concepts Practice Questions for Midterm 1 March 11, 2018 Question 1: Identify the common elements of two sorted

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. The Collection Framework

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. The Collection Framework Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani The Collection Framework Collection: an aggregate that can hold a varying number of elements Interface:

More information

Java Collections Framework. 24 April 2013 OSU CSE 1

Java Collections Framework. 24 April 2013 OSU CSE 1 Java Collections Framework 24 April 2013 OSU CSE 1 Overview The Java Collections Framework (JCF) is a group of interfaces and classes similar to the OSU CSE components The similarities will become clearly

More information

Outline. iterator review iterator implementation the Java foreach statement testing

Outline. iterator review iterator implementation the Java foreach statement testing Outline iterator review iterator implementation the Java foreach statement testing review: Iterator methods a Java iterator only provides two or three operations: E next(), which returns the next element,

More information

Another IS-A Relationship

Another IS-A Relationship Another IS-A Relationship Not all classes share a vertical relationship. Instead, some are supposed to perform the specific methods without a vertical relationship. Consider the class Bird inherited from

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Generic Programming Recursive Binary Search SESSION 9. Programming Languages for Objects

Generic Programming Recursive Binary Search SESSION 9. Programming Languages for Objects SESSION 9 Programming Languages for Objects Generic Programming Lists and Sets Maps Programming with the Java Collection Framework Writing Generic Classes and Methods Generic Programming.1.1 Recursive

More information

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Inheritance Abstract classes Interfaces instanceof operator Nested classes Enumerations COUSE CONTENT Collections List Map Set Aggregate

More information

egrapher Language Reference Manual

egrapher Language Reference Manual egrapher Language Reference Manual Long Long: ll3078@columbia.edu Xinli Jia: xj2191@columbia.edu Jiefu Ying: jy2799@columbia.edu Linnan Wang: lw2645@columbia.edu Darren Chen: dsc2155@columbia.edu 1. Introduction

More information

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CS121/IS223. Object Reference Variables. Dr Olly Gotel CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223

More information

Generic classes & the Java Collections Framework. *Really* Reusable Code

Generic classes & the Java Collections Framework. *Really* Reusable Code Generic classes & the Java Collections Framework *Really* Reusable Code First, a bit of history Since Java version 5.0, Java has borrowed a page from C++ and offers a template mechanism, allowing programmers

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All This chapter discusses class String, from the java.lang package. These classes provide the foundation for string and character manipulation

More information

Need to access each element of a list. Use index to access an element of the list. It s quadratic, while:

Need to access each element of a list. Use index to access an element of the list. It s quadratic, while: ! " # $ $ % & ' () * + (, -. /* 0 * / (1 2 3-4 1 5 6 5 ' 7 8 * / 9 : ; < 8 * /' 8 - /4 J K L M N O PQ M R S After studying this chapter you should understand the following: the role of iterators in container

More information

JAVA WRAPPER CLASSES

JAVA WRAPPER CLASSES JAVA WRAPPER CLASSES Description Each of Java's eight primitive data types has a class dedicated to it. These are known as wrapper classes, because they "wrap" the primitive data type into an object of

More information

Data Structure. Recitation IV

Data Structure. Recitation IV Data Structure Recitation IV Topic Java Generics Java error handling Stack Lab 2 Java Generics The following code snippet without generics requires casting: List list = new ArrayList(); list.add("hello");

More information