Vectors - PowerPoint PPT Presentation

About This Presentation
Title:

Vectors

Description:

... or a telephone directory (a collection of name-to-phone-number mappings) ... reverse(List) fill(List, Object) copy(List dest, List src) binarySearch(List, Object) ... – PowerPoint PPT presentation

Number of Views:55
Avg rating:3.0/5.0
Slides: 35
Provided by: mathew
Learn more at: http://www.cs.ucf.edu
Category:

less

Transcript and Presenter's Notes

Title: Vectors


1
Vectors
  • and the Collections Framework

2
Vectors
  • A Vector is a growable array of objects.
  • You can access elements using an integer index,
    just like arrays.
  • A Vector grows and shrinks as needed.
  • It has an initial capacity and a
    capacityIncrement.
  • When capacity is too small, it increases the size
    of the Vector by capacityIncrement.

3
Vector Example
  • import java.util.
  • public class VectorUsage
  • public static void main(String args)
  • // create Vector with default initial
    capacity
  • Vector v new Vector()
  • // add 4 objects
  • v.add("hello")
  • v.add("good morning")
  • v.add("good night")
  • v.add("later")
  • System.out.println(v.elementAt(1))
  • Ouput good morning

4
Wrapper Classes
  • Vectors (and all other collections) can only hold
    Objects. How can we store primitive data in
    Vectors?
  • Use wrapper classes!
  • Need to store an int? Use Integer!
  • Need to store a boolean? Use Boolean!

5
Collections
  • A collection (sometimes called a container) is
    simply an object that groups multiple elements
    into a single unit.
  • Collections typically represent data items that
    form a natural group, like a poker hand (a
    collection of cards), a mail folder (a collection
    of letters), or a telephone directory (a
    collection of name-to-phone-number mappings).

6
Collections Framework
  • A collections framework is a unified architecture
    for representing and manipulating collections.
  • It contains 3 things
  • interfaces methods of collections are declared
    in interfaces for example, all collections have
    an isEmpty() behavior
  • implementations different collection classes
    implement the collection interfaces
  • algorithms for example, searching and sorting
    algorithms coded to an interface, not any one
    implementation lots of reuse!

7
Benefits of a Framework
  • Reduced programming effort.
  • No need to code your own collections.
  • Increased program speed and quality.
  • Javas collections are fast and reliable.
  • Interoperability among unrelated APIs.
  • Collections can be used everywheree.g. read from
    a file, pass collection to a GUI component
  • Common API.
  • Users only need to learn one API.
  • New implementations code to the interfaces.
  • Implementers only need to learn one API.
  • Fosters software reuse.
  • New data structures that conform to the
    interfaces are reusable.

8
Core Collection Interfaces
9
Collection Interface
  • Root of the collection hierarchy.
  • Some Collection implementations allow duplicate
    elements and others do not.
  • Some are ordered and others unordered.
  • Collection is used to pass collections around and
    manipulate them when maximum generality is
    desired.

10
Collection Interface
  • public interface Collection
  • int size()
  • boolean isEmpty()
  • boolean contains(Object element)
  • boolean add(Object element)
  • boolean remove(Object element)
  • Iterator iterator()
  • boolean containsAll(Collection c)
  • boolean addAll(Collection c)
  • removeAll(Collection c)
  • boolean retainAll(Collection c)
  • void clear()
  • Object toArray()
  • Object toArray(Object a)

11
Iterator Interface
  • An Iterator is a way to enumerate all the
    elements in a Collection.
  • Its analogous to iterating through the indices
    of an array.
  • public interface Iterator
  • boolean hasNext()
  • Object next()
  • void remove() // Optional

12
Iterator Interface
  • hasNext returns true if the underlying
    Collection has at least one more element
  • next returns the next element
  • remove deletes the element returned by the last
    next method call this is the only safe way to
    remove elements during iteration

13
Iterator Example
  • // assume an existing Collection object c
  • Iterator iter c.iterator()
  • while (iter.hasNext())
  • System.out.println(iter.next())

14
Bulk Operations on Collections
  • containsAll Returns true if the target
    Collection contains all of the elements in the
    specified Collection.
  • addAll Adds all of the elements in the specified
    Collection to the target Collection.
  • removeAll Removes from the target Collection all
    of its elements that are also contained in the
    specified Collection.
  • retainAll Removes from the target Collection all
    of its elements that are not also contained in
    the specified Collection. That is to say, it
    retains only those elements in the target
    Collection that are also contained in the
    specified Collection.
  • clear Removes all elements from the Collection.

15
Array Operations on Collections
  • Array operations allow the contents of a
    Collection to be translated into an array.
  • For example, suppose c is a Collection.The
    following snippet dumps the contents of c into a
    newly allocated array of Object whose length is
    identical to the number of elements in c
  • Object a c.toArray()

16
Sets
  • A Set is a Collection that cannot contain
    duplicate elements.
  • Set models the mathematical set abstraction.
  • JDK provides two implementations
  • HashSet based on hash table fastest
  • TreeSet based on red-black tree guarantees
    order of iteration

17
Set Example
  • import java.util.
  • public class FindDups
  • public static void main(String args)
  • Set s new HashSet()
  • for (int i0 i
  • if (!s.add(argsi))
  • System.out.println("Duplicate detected
    argsi)
  • System.out.println(s.size() " distinct
    words detected "s)
  • // for
  • // now run it from command line
  • java FindDups i came i saw i left
  • Duplicate detected i
  • Duplicate detected i
  • 4 distinct words detected came, left, saw, i

18
Bulk Operations on Sets
  • s1.containsAll(s2) Returns true if s2 is a
    subset of s1.
  • s1.addAll(s2) Transforms s1 into the union of s1
    and s2.
  • s1.retainAll(s2) Transforms s1 into the
    intersection of s1 and s2.
  • s1.removeAll(s2) Transforms s1 into the
    (asymmetric) set difference of s1 and s2.

19
Sets
  • Note that in the previous example, the code
    always referred to the collection using the
    interface (Set) and not its implementation
    (HashSet).
  • This allows us to switch between implementations
    by changing the constructor.

20
Lists
  • A List is an ordered Collection (sometimes called
    a sequence).
  • Lists may contain duplicate elements.
  • Lists go beyond the Collection behaviors
  • Positional Access manipulate elements based on
    their numerical position in the list.
  • Search search for a specified object in the list
    and return its numerical position.
  • List Iteration extend Iterator semantics to take
    advantage of the list's sequential nature.
  • Range-view perform arbitrary range operations on
    the list.

21
List Interface
  • public interface List extends Collection
  • Object get(int index)
  • Object set(int index, Object element)
  • void add(int index, Object element)
  • Object remove(int index)
  • abstract boolean addAll(int index, Collection
    c)
  • int indexOf(Object o)
  • int lastIndexOf(Object o)
  • ListIterator listIterator()
  • ListIterator listIterator(int index)
  • List subList(int from, int to)

22
List Example
  • Heres the classic swap using List operations
  • private static void swap(List a, int i, int j)
  • Object tmp a.get(i)
  • a.set(i, a.get(j))
  • a.set(j, tmp)
  • Notice this algorithm is polymorphic it can
    operate on any List.

23
List Example
  • The following operation removes a range of
    elements from a list
  • list.subList(fromIndex, toIndex).clear()

24
ListIterator Interface
  • public interface ListIterator extends Iterator
    boolean hasNext()
  • Object next()
  • boolean hasPrevious()
  • Object previous()
  • int nextIndex()
  • int previousIndex()
  • void remove()
  • void set(Object o)
  • void add(Object o)

25
ListIterator Example
  • // assume we have a List called list
  • // iterate the List backwards
  • // note for statement is broken into multiple
    lines
  • for (ListIterator ilist.listIterator(list.size())
    i.hasPrevious() )
  • Foo f (Foo) i.previous()
  • ...
  • Note that the return value of previous is an
    Object. We must downcast to Foo in order to call
    Foo methods.

26
List Interface
  • JDK provides two implementations of the List
    interface
  • ArrayList
  • LinkedList
  • Vector has been retrofitted to implement List.

27
Polymorphic Algorithms
  • Remember, we said that one of the components of a
    collections framework is algorithms.
  • Below are some example algorithms that operate on
    any List
  • sort(List)
  • shuffle(List)
  • reverse(List)
  • fill(List, Object)
  • copy(List dest, List src)
  • binarySearch(List, Object)

28
Maps
  • A Map is an object that maps keys to values.
  • A map cannot contain duplicate keys.
  • Each key can map to at most one value.

29
Map Interface
  • public interface Map
  • Object put(Object key, Object value)
  • Object get(Object key)
  • Object remove(Object key)
  • boolean containsKey(Object key)
  • boolean containsValue(Object value)
  • int size()
  • boolean isEmpty()
  • void putAll(Map t)
  • void clear()
  • Set keySet()
  • Collection values()
  • Set entrySet()

30
Maps
  • JDK provides two implementations of Map
  • HashMap based on a hash table faster
  • TreeMap based on red-black tree guarantees
    order of iteration

31
Map Example
  • import java.util.
  • public class Freq
  • private static final Integer ONE new
    Integer(1)
  • public static void main(String args)
  • Map m new HashMap()
  • for (int i0 i
  • Integer freq (Integer) m.get(argsi)
  • m.put(argsi, (freqnull ? ONE new
    Integer(freq.intValue() 1)))
  • System.out.println(m.size()" distinct words
    detected")
  • System.out.println(m)

32
Map Example (continued)
  • Now from the command line
  • java Freq if it is to be it is up to me to
    delegate
  • Output is
  • 8 distinct words detected to3, me1,
    delegate1, it2, is2, if1, be1, up1

33
Summary
Implementations
Interfaces
34
Works Cited
  • JavaTM 2 Platform Std. Ed. v1.4.1 API
    documentation. http//java.sun.com/j2se/1.4.1/docs
    /api/
  • The Java Tutorial. Collections Trail.
    http//java.sun.com/docs/books/tutorial/collection
    s/index.html
Write a Comment
User Comments (0)
About PowerShow.com