Download presentation
Presentation is loading. Please wait.
Published byElizabeth Fowler Modified over 8 years ago
1
Holding Your Objects 2016-5-301
2
Generics and type-safe containers One of the problems of using pre-Java SE5 containers was that the compiler allowed you to insert an incorrect type into a container. define an ArrayList intended to hold Apple objects, you say ArrayList instead of just ArrayList. The angle brackets surround the type parameters (there may be more than one), which specify the type(s) that can be held by that instance of the container. With generics, you’re prevented, at compile time, from putting the wrong type of object into a container 2016-5-302
3
Basic concepts The Java container library takes the idea of "holding your objects" and divides it into two distinct concepts, expressed as the basic interfaces of the library. 1. Collection: a sequence of individual elements with one or more rules applied to them. 2. Map: a group of key-value object pairs, allowing you to look up a value using a key. 2016-5-303
4
A List must hold the elements in the way that they were inserted. A Set cannot have duplicate elements. A Queue produces the elements in the order determined by a queuing discipline (usually the same order in which they are inserted). 2016-5-304
5
A map allows you to look up an object using another object. It’s also called an associative array, because it associates objects with other objects, or a dictionary, because you look up a value object using a key object just like you look up a definition using a word. Maps are powerful programming tools. 2016-5-305
6
Although it’s not always possible, ideally you’ll write most of your code to talk to these interfaces, and the only place where you’ll specify the precise type you’re using is at the point of creation. The intent of using the interface is that if you decide you want to change your implementation, all you need to do is change it at the point of creation 2016-5-306
7
Adding groups of elements There are utility methods in both the Arrays and Collections classes in java.util that add groups of elements to a Collection. Arrays.asList( ) takes either an array or a comma-separated list of elements (using varargs) and turns it into a List object. 2016-5-307
8
Collections.addAll( ) takes a Collection object and either an array or a comma-separated list and adds the elements to the Collection. Here’s an example that shows both methods, as well as the more conventional addAll( ) method that’s part of all Collection types 2016-5-308
9
Printing containers You must use Arrays.toString( ) to produce a printable representation of an array, but the containers print nicely without any help. In the output, you can see that the default printing behavior (provided via each container’s toString( ) method) produces reasonably readable results. A Collection is printed surrounded by square brackets, with each element separated by a comma. A Map is surrounded by curly braces, with each key and value associated with an equal sign (keys on the left, values on the right). 2016-5-309
10
List Lists promise to maintain elements in a particular sequence. The List interface adds a number of methods to Collection that allow insertion and removal of elements in the middle of a List. 2016-5-3010
11
There are two types of List: The basic ArrayList, which excels at randomly accessing elements, but is slower when inserting and removing elements in the middle of a List. The LinkedList, which provides optimal sequential access, with inexpensive insertions and deletions from the middle of the List. A LinkedList is relatively slow for random access, but it has a larger feature set than the ArrayList. 2016-5-3011
12
Iterator In any container, you must have a way to insert elements and fetch them out again. The concept of an Iterator (another design pattern) can be used to achieve this abstraction. An iterator is an object whose job is to move through a sequence and select each object in that sequence without the client programmer knowing or caring about the underlying structure of that sequence. In addition, an iterator is usually what’s called a lightweight object: one that’s cheap to create. 2016-5-3012
13
ListIterator The ListIterator is a more powerful subtype of Iterator that is produced only by List classes. While Iterator can only move forward, ListIterator is bidirectional. It can also produce the indexes of the next and previous elements relative to where the iterator is pointing in the list, and it can replace the last element that it visited using the set( ) method. 2016-5-3013
14
LinkedList The LinkedList also implements the basic List interface like ArrayList does, but it performs certain operations (insertion and removal in the middle of the List) more efficiently than does ArrayList. Conversely, it is less efficient for random-access operations. 2016-5-3014
15
Stack A stack is sometimes referred to as a "last-in, first-out" (LIFO) container. It’s sometimes called a pushdown stack, because whatever you "push" on the stack last is the first item you can "pop" off of the stack. An often-used analogy is of cafeteria trays in a spring-loaded holder—the last ones that go in are the first ones that come out. 2016-5-3015
16
Set A Set refuses to hold more than one instance of each object value. If you try to add more than one instance of an equivalent object, the Set prevents duplication. The most common use for a Set is to test for membership, so that you can easily ask whether an object is in a Set. Because of this, lookup is typically the most important operation for a Set, so you’ll usually choose a HashSet implementation, which is optimized for rapid lookup. 2016-5-3016
17
Map The ability to map objects to other objects can be an immensely powerful way to solve programming problems. For example, consider a program to examine the randomness of Java’s Random class. Ideally, Random would produce a perfect distribution of numbers, but to test this you need to generate many random numbers and count the ones that fall in the various ranges. A Map easily solves the problem; in this case, the key is the number produced by Random, and the value is the number of times that number appears 2016-5-3017
18
Queue A queue is typically a “first-in, first-out" (FIFO) container. That is, you put things in at one end and pull them out at the other, and the order in which you put them in will be the same order in which they come out. Queues are commonly used as a way to reliably transfer objects from one area of a program to another. Queues are especially important in concurrent programming, as you will see in the Concurrency chapter, because they safely transfer objects from one task to another. 2016-5-3018
19
PriorityQueue First-in, first-out (FIFO) describes the most typical queuing discipline. A queuing discipline is what decides, given a group of elements in the queue, which one goes next. First-in, first-out says that the next element should be the one that was waiting the longest. A priority queue says that the element that goes next is the one with the greatest need (the highest priority). 2016-5-3019
20
Collection vs. Iterator Collection is the root interface that describes what is common for all sequence containers. It might be thought of as an "incidental interface," one that appeared because of commonality between other interfaces. The use of Iterator becomes compelling when you implement a foreign class, one that is not a Collection, in which it would be difficult or annoying to make it implement the Collection interface. 2016-5-3020
21
Foreach and iterators So far, the foreach syntax has been primarily used with arrays, but it also works with any Collection object. The reason that this works is that Java SE5 introduced a new interface called Iterable which contains an iterator( ) method to produce an Iterator, and the Iterable interface is what foreach uses to move through a sequence. 2016-5-3021
22
The Adapter Method idiom The "Adapter" part comes from design patterns, because you must provide a particular interface to satisfy the foreach statement. When you have one interface and you need another one, writing an adapter solves the problem. Here, I want to add the ability to produce a reverse iterator to the default forward iterator, so I can’t override. Instead, I add a method that produces an Iterable object which can then be used in the foreach statement. As you see here, this allows us to provide multiple ways to use foreach. 2016-5-3022
23
Summary Java provides a number of ways to hold objects: 1. An array associates numerical indexes to objects. It holds objects of a known type so that you don’t have to cast the result when you’re looking up an object. It can be multidimensional, and it can hold primitives. However, its size cannot be changed once you create it. 2016-5-3023
24
2. A Collection holds single elements, and a Map holds associated pairs. 3. Like an array, a List also associates numerical indexes to objects 4. Use an ArrayList if you’re doing a lot of random accesses, but a LinkedList if you will be doing a lot of insertions and removals in the middle of the list. 5. The behavior of Queues and stacks is provided via the LinkedList. 6. A Map is a way to associate not integral values, but objects with other objects. 7. A Set only accepts one of each type of object. 8. There’s no need to use the legacy classes Vector, Hashtable, and Stack in new code. 2016-5-3024
25
Simple Container Taxonomy 2016-5-3025
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.