Download presentation
Presentation is loading. Please wait.
Published byDwight Wilson Modified over 9 years ago
1
Object Oriented Programming and Data Abstraction Rowan University Earl Huff
2
A collection is an object which groups multiple elements into a single unit. Collections store, retrieve, manipulate and communicate data. Represent items from a natural group (i.e. a poker hand, phone directory, student record system.
3
A unified architecture for representing and manipulating collections. All frameworks contain: Interfaces – allow collections to be manipulated independently of the details of their representation. Implementations – concrete implementations of collection interfaces. Algorithms – methods performing computations. They are polymorphic; can be used on many different implementations of interface.
4
Benefits of the Java Collections Framework include Reduces programming effort Increases program speed and quality Allows interoperability among unrelated APIs Reduces effort to learn and to use new APIs Fosters software resuse
5
CollectionSetSortedSetListQueueDeque MapSortedMap
6
The root interface in the collection hierarchy. Used to pass around collections of objects where generality is desired. All collection implementations have a constructor that’s a Collection argument called the conversion constructor. Initialize the new collection containing all elements in specified collection, whatever the collection’s implementation or subinterface type.
7
Collection c; //could be List, Set, or another type //of collection List list = new ArrayList (c);
8
Basic Methods size() isEmpty() contains(Object element) add (E element) remove(Object element) iterator() Bulk Methods containsAll() addAll() removeAll() retainAll() clear() Array Methods toArray()
9
Three ways to traverse collections: Aggregate Operations For-each loop Interators
10
myShapesCollection.stream().filter(e -> e.getColor() == Color.RED).forEach(e-> System.out.println(e.getName()));
11
for (Object o : collection) { System.out.println(o); }
12
Iterator it = c.iterator(); while (it.hasNext()) { if (cond(it.next())) it.remove(); }
13
A Set is a kind of Collection that does not contain duplicate elements. Models the mathematical set abstraction. Contains only methods inherited from Collection and adds the restriction of prohibiting duplicate elements. Places strong stipulation on contract of all constructors and the add, equals, and hashCode methods. Three implementations HashSet – best performing TreeSet – slower than Hashset but faster than LinkedHashSet LinkedHashSet – a hashtable with a linked list running through it.
14
A list is an ordered Collection (sometimes called a sequence). A list can have duplicate elements. Elements in a list can be accessed by their integer index. Elements in a list can be searched for.
15
In addition to methods inherited from Collection, the List interface includes methods for: Positional access – get, set, add, addAll, and remove Search – indexOf and lastIndexOf Iteration - listIterator
16
A Queue is a collection for holding elements prior to processing. In addition to basic Collection operations, queues provide operations for insertion, removal, and inspection. Each Queue method has two forms: One throws an exception if the operation fail. One returns either null or false if the operation fails.
17
Throws Exception add(e) remove() element() Returns Special Value offer(e) poll() peek()
18
Queues typically, but not necessarily, order elements in a FIFO (first-in-first-out) manner. Priority queues are the exception. Regardless of the ordering, the head of the element is the element which will be removed by a call to remove() or poll(). offer and add will add an element to the queue if possible. remove and poll will remove and return the head of the queue if possible. element and peek will return, but not remove, the head of the queue.
19
Pronounced “deck” A double-ended-queue A linear collection that supports insertion and removal of elements at both end points. Implements both Stack and Queue at the same time. Methods are provided to insert, remove, and examine elements as well as access elements at both ends. Implementations of Deque are ArrayDeque and LinkedList
20
Deque methods are divided into three parts: Insert addFirst(e), offerFirst(e), addLast(e), offerLast(e) Remove removeFirst(), pollFirst(), removeLast(), pollLast() Examine/Retrieve getFirst(), peekFirst(), getLast(), peekLast()
21
A Map is an object that maps keys to values. A key is a unique index to a value. Only one key per value. A Map cannot contain duplicate keys. Implementations of Map HashMap TreeMap LinkedHashMap Behavior and performance are analogous to their Set counterparts.
22
Basic Operations put, get, remove, containsKey, containsValue, size, empty Bulk Operations putsAll, clear Collection Views keySet, values, entrySet
23
Provides a natural ordering for class so objects can be sorted. Lists (and arrays) of objects implementing the interface is sorted automatically by Collections.sort (and Arrays.sort). Highly recommended that natural orderings are consistent with the equals method. The natural ordering for a class C is consistent with equals if and only if e1.compareTo(e2) == 0 has the same Boolean value as e1.equals(e2) for every e1 and e1 of class C.
24
Compares the receiving object with the invoking object. Returns: 0 – they are equal Positive integer – invoking object is greater than Negative integer – invoking object is less than A ClassCastException is thrown if invoking object cannot be compared to receiving object.
25
You can write your own Comparable types You can override equals* and compareTo methods *If you override equals, you must also redefine hashCode method. Equal objects must have equal hash codes! Comparator Interface Alternative to Comparable Uses a different kind of ordering for a collection of objects. Consist of one method: compare(T o1, To2)
26
SortedSet – a set that maintains its elements in ascending order, sorted to either the elements’ natural ordering or to a Comparator. SortedMap – a map that maintains its entries in ascending order of the keys… Both add methods, in addition to their respective superclass methods, for the following operations: Range view – arbitrary range operations on the sorted collection Endpoints – returning first or last element in the sorted collection Comparator access – return the Comparator used to sort the set
27
SortedSet Range-view subSet(E fromElement, E toElement) headSet(E toElement) tailSet(E fromElement) Endpoints E first() E last() Comparator access Comparator comparator() SortedMap Range-view subMap(K formKey, K toKey) headMap(K toKey) tailMap(K fromKey) Endpoints K firstKey() K lastKey() Comparator access Comparator comparator()
28
In most applications, it will be necessary to obtain input from the user. Input can come from a variety of sources (i.e. keyboard input, text file, etc.) Java provides a variety of tools to read data from different input sources. Focus will be on keyboard input for now.
29
Reader class is the root class for the hierarchy of readers for reading character streams. The only methods the subclasses can override are the variations of read() and close(). Notable subclasses BufferedReader, FileReader, InputStreamReader All readers can be fond in the Java.io package
30
BufferedReader classes allows for reading text from a character-input stream. Creates a buffer, providing efficient reading of characters, arrays, and lines. Ideal to wrap a BufferedReader around other Readers to avoid costly read() operations. For keyboard input, often users wrap BufferedReader around InputStreamReader, which takes System.in (the standard keyboard input stream) as an argument for its constructor)
31
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parsetInt(in.readLine());
32
Scanner is the alternative, though more often used, method to reading user input. Can be found in the Java.util package. Performs the same way and at the same level of efficiency of BufferedReader. Difference is that Scanner can parse primitive types and strings with the use of regular expressions. (i.e. nextInt(), nextLong(), etc.) Scanner can break input into tokens using a delimiter pattern
33
Scanner sc = new Scanner(System.in); int i = sc.nextInt();
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.