Presentation is loading. Please wait.

Presentation is loading. Please wait.

©Karsten Lundqvist Example: Array and Arrays 1 import java.util.*; public class Example { private int intValues[] = { 1, 2, 3, 4, 5, 6 }; private double.

Similar presentations


Presentation on theme: "©Karsten Lundqvist Example: Array and Arrays 1 import java.util.*; public class Example { private int intValues[] = { 1, 2, 3, 4, 5, 6 }; private double."— Presentation transcript:

1 ©Karsten Lundqvist Example: Array and Arrays 1 import java.util.*; public class Example { private int intValues[] = { 1, 2, 3, 4, 5, 6 }; private double doubleValues[] = { 8.4, 9.3, 0.2, 7.9, 3.4 }; private int filledInt[], intValuesCopy[]; public Example() { filledInt = new int[ 10 ]; intValuesCopy = new int[ intValues.length ]; Arrays.fill( filledInt, 7 ); // fill with 7s Arrays.sort( doubleValues ); // sort doubleValues ascending // copy array intValues into array intValuesCopy System.arraycopy( intValues, 0, intValuesCopy, 0, intValues.length ); } Use static method fill of class Arrays to populate array with 7 s Use static method sort of class Arrays to sort array’s elements in ascending order Use static method arraycopy of class System to copy array intValues into array intValuesCopy

2 ©Karsten Lundqvist The Java Collections Framework The Java collections framework is made up of a set of interfaces and classes for working with groups of objects The Java Collections Framework provides Interfaces: abstract data types representing collections. Implementations: concrete implementations of the collection interfaces. Algorithms: methods that perform useful computations, like searching and sorting, on objects that implement collection interfaces. More information: 2 http://java.sun.com/docs/books/tutorial/collections/

3 ©Karsten Lundqvist JCF A collection represents a group of objects known as its elements. The Collection interface is the least common denominator that all collections implement and is used to pass collections around and to manipulate them when maximum generality is desired. Some types of collections allow duplicate elements, and others do not. Set: a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction. List: an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position). If you've used Vector, you're familiar with the general flavor of List. Queue: a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations. (E.g., a FIFO queue) Map: an object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value. If you've used Hashtable, you're already familiar with the basics of Map. 3

4 ©Karsten Lundqvist Collections 4

5 ©Karsten Lundqvist Maps 5

6 ©Karsten Lundqvist Interface Collection 6 // Basic Operations size():int; isEmpty():boolean; contains(Object):boolean; add(Object):boolean; // Optional remove(Object):boolean; // Optional iterator():Iterator; // Bulk Operations containsAll(Collection):boolean; addAll(Collection):boolean; // Optional removeAll(Collection):boolean; // Optional retainAll(Collecton):boolean; // Optional clear():void; // Optional // Array Operations toArray():Object[]; toArray(Object[]):Object[]; Collection Found in the java.util package Optional methods throw UnsupportedOperationException if the implementing class does not support the operation. Bulk operations perform some operation on an entire Collection in a single shot The toArray methods allow the contents of a Collection to be translated into An array.

7 ©Karsten Lundqvist Interface Set A Set is a Collection that cannot contain duplicate elements. Set models the mathematical set abstraction. The Set interface extends Collection and contains no methods other than those inherited from Collection It adds the restriction that duplicate elements are prohibited. Two Set objects are equal if they contain the same elements. 7

8 ©Karsten Lundqvist Interface List Elements in a list are ordered By insertion sequence, if nothing else By magnitude, alphabetical order, etc. A list can contain duplicate entries e.g., a list of purchased items can include the same item more than once. 8 // Positional Access get(int):Object; set(int,Object):Object; // Optional add(int, Object):void;// Optional remove(int index):Object; // Optional addAll(int, Collection):boolean;// Optional // Search int indexOf(Object); int lastIndexOf(Object); // Iteration listIterator():ListIterator; listIterator(int):ListIterator; // Range-view List subList(int, int):List;

9 ©Karsten Lundqvist Interface Queue A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations. Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner. Deque: A linear collection that supports element insertion and removal at both ends. The name deque is short for "double ended queue" 9 ValueThrows Exception Returns special value Insert : add(e) offer(e) Remove : remove() poll() Examine : element() peek()

10 ©Karsten Lundqvist Interface Map A map is a set of pairs each pair represents a one-directional “mapping” from one object (the key) to another (the value) The typical use of a Map is to provide access to values stored by key. Some examples: A map of student IDs to database records A dictionary (words mapped to meanings) The conversion from base 2 to base 10 Names to phone numbers 10 … Object k,v;  clear() Remove all mappings  containsKey(k) Whether contains a mapping for k  containsValue(v) Whether contains a mapping to v  entrySet() Set of key-value pairs  get(k) The value associated with k  isEmpty() Whether it is empty  keySet() Set of keys  put(k,v) Associate v with k  remove(k) Remove the mapping for k  size() The number of pairs  values() The collection of values

11 ©Karsten Lundqvist Concrete Collections concrete implements description collection HashSet Set hash table TreeSet SortedSet balanced binary tree ArrayList List resizable-array LinkedList List linked list Vector List resizable-array HashMap Map hash table TreeMap SortedMap balanced binary tree Hashtable Map hash table ArrayDequeDequedouble ended resizable-array 11

12 ©Karsten Lundqvist Concrete Collections 12 InterfaceImplementationHistorical SetHashSetTreeSet ListArrayListLinkedList Vector Stack DequeArrayDequeLinkedList MapHashMapTreeMapHashTable Properties Note: When writing programs think about interfaces and not implementations. This way the program does not become dependent on any added methods in a given implementation, leaving the programmer with the freedom to change implementations.

13 ©Karsten Lundqvist ArrayList public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, Serializable Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.) 13    

14 ©Karsten Lundqvist LinkedList public class LinkedList extends AbstractSequentialList implements List, Deque, Cloneable, Serializable Linked list implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface, the LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue. The class implements the Deque interface, providing first-in-first-out queue operations for add, poll, along with other stack and deque operations. All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index. 14  first last

15 ©Karsten Lundqvist Ordering and Sorting There are two ways to define orders on objects. Each class can define a natural order among its instances by implementing the Comparable interface. int compareTo(Object o) Arbitrary orders among different objects can be defined by comparators, classes that implement the Comparator interface. int compare(Object o1, Object o2) Use the sort method in the Class Collections: Collections.sort(myConcreteCollection); Collections.sort(myConcreteCollection, myCompatarator); Other methods include: shuffle, reverse, fill, binarySearch, frequency... 15


Download ppt "©Karsten Lundqvist Example: Array and Arrays 1 import java.util.*; public class Example { private int intValues[] = { 1, 2, 3, 4, 5, 6 }; private double."

Similar presentations


Ads by Google