Collections - PowerPoint PPT Presentation

1 / 46
About This Presentation
Title:

Collections

Description:

Java collections framework. Access to prepackaged data structures ... operations on the entire collection ... Static methods of the Collections class ... – PowerPoint PPT presentation

Number of Views:49
Avg rating:3.0/5.0
Slides: 47
Provided by: joek8
Category:

less

Transcript and Presenter's Notes

Title: Collections


1
Collections
  • Joe Komar

2
Overview
  • Arrays class
  • Collection Interface and Collections class
  • Lists
  • Algorithms
  • Sets
  • Maps
  • Wrappers
  • Abstract Implementations

3
Java collections framework
  • Access to prepackaged data structures
  • Algorithms for manipulating data structures
  • Provides broad reuse of code
  • Tuned for efficient execution and use of memory

4
Arrays class
  • Provides static methods for manipulating arrays
  • Can manipulate arrays of primitive data types and
    of objects
  • Built in functionality for such things as
    searching, sorting, and filling arrays

5
Arrays methods
List asList(Object a) int binarySearch(primitive
p, key k) int binarySearch(Object o, key
k) boolean equals(primitive p1, primitive
p2) boolean equals(Object o1, Object o2) void
fill(primitive p, primitiveValue v) void
fill(primitive p, int fromIndex, int toIndex,
primitiveValue v) void fill(Object o, Object
v) void fill(Object o, int fromIndex, int
toIndex, Object v) void sort(primitive p) void
sort(primitive p, int fromIndex, int
toIndex) void sort(Object o) void sort(Object
o, int fromIndex, int toIndex)
6
Arrays example
import java.util. public class UsingArrays
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
7
Arrays example
public UsingArrays() filledInt new
int 10 intValuesCopy new int
intValues.length Arrays.fill( filledInt,
7 ) // fill with 7s Arrays.sort(
doubleValues ) // sort doubleValues
System.arraycopy( intValues, 0, intValuesCopy,
0, intValues.length )
8
Arrays example
public void printArrays()
System.out.print( "doubleValues " ) for (
int k 0 k lt doubleValues.length k )
System.out.print( doubleValues k " " )
System.out.print("\nintValues " ) for (
int k 0 k lt intValues.length k )
System.out.print( intValues k " " )
System.out.print("\nfilledInt " ) for (
int k 0 k lt filledInt.length k )
System.out.print( filledInt k " " )
System.out.print("\nintValuesCopy " ) for
( int k 0 k lt intValuesCopy.length k )
System.out.print( intValuesCopy k " "
) System.out.println()
9
Arrays example
public int searchForInt( int value )
return Arrays.binarySearch( intValues, value )
public void printEquality()
boolean b Arrays.equals( intValues,
intValuesCopy ) System.out.println(
"intValues " ( b ? "" "!" )
" intValuesCopy" ) b
Arrays.equals( intValues, filledInt )
System.out.println( "intValues " ( b ? ""
"!" ) " filledInt"
)
10
Arrays example
public static void main( String args )
UsingArrays u new UsingArrays()
u.printArrays() u.printEquality()
int n u.searchForInt( 5 )
System.out.println( ( n gt 0 ? "Found 5 at
element " n "5 not
found" ) " in intValues" ) n
u.searchForInt( 8763 ) System.out.println(
( n gt 0 ? "Found 8763 at element "
n "8763 not found" )
" in intValues" )
11
Arrays example
doubleValues 0.2 3.4 7.9 8.4 9.3 intValues 1 2
3 4 5 6 filledInt 7 7 7 7 7 7 7 7 7
7 intValuesCopy 1 2 3 4 5 6 intValues
intValuesCopy intValues ! filledInt Found 5 at
element 4 in intValues 8763 not found in intValues
12
asList method
import java.util. public class UsingAsList
private String values "red", "white",
"blue" private List theList public
UsingAsList() theList Arrays.asList(
values ) // get List theList.set( 1,
"green" ) // change a value
13
asList method
public void printElements()
System.out.print( "List elements " ) for
( int k 0 k lt theList.size() k )
System.out.print( theList.get( k ) " " )
System.out.print( "\nArray elements " )
for ( int k 0 k lt values.length k )
System.out.print( values k " " )
System.out.println() public static void
main( String args ) new
UsingAsList().printElements()
14
asList method
List elements red green blue Array elements
red green blue
15
Collection Interface
  • Root interface for Set and List
  • Contains bulk operations -- operations on the
    entire collection
  • Provides for conversion to an array
  • Method to generate an Iterator object
  • similar to Enumerator but with the ability to
    remove elements
  • Methods for size, hash code, is empty

16
List Interface
  • Derived from Collection interface
  • Unordered collection sometimes called a
    sequence
  • Allows duplicate items
  • Can manipulate elements using their indices
  • Can manipulate a range of elements
  • Search elements
  • Create a ListIterator to access elements

17
List implementations
  • ArrayList
  • resizable array similar to Vector
  • LinkedList
  • a linked set of elements
  • Vector

18
ArrayList example
import java.util. import java.awt.Color public
class CollectionTest private String colors
"red", "white", "blue" public
CollectionTest() ArrayList aList new
ArrayList() aList.add( Color.magenta )
// add a color object for ( int k 0 k lt
colors.length k ) aList.add( colors
k ) aList.add( Color.cyan ) //
add a color object System.out.println(
"\nArrayList " ) for ( int k 0 k lt
aList.size() k ) System.out.print(
aList.get( k ) " " )
19
ArrayList example
removeStrings( aList )
System.out.println( "\n\nArrayList after calling
removeStrings " ) for ( int k 0 k lt
aList.size() k ) System.out.print(
aList.get( k ) " " ) public void
removeStrings( Collection c ) Iterator
i c.iterator() // get iterator while
( i.hasNext() ) // loop while collection
has items if ( i.next() instanceof
String ) i.remove() //
remove String object public static void
main( String args ) new
CollectionTest()
20
ArrayList example
ArrayList java.awt.Colorr255,g0,b255 red
white blue java.awt.Colorr0,g255,b255 ArrayL
ist after calling removeStrings java.awt.Colorr
255,g0,b255 java.awt.Colorr0,g255,b255
21
LinkedList example
import java.util. public class ListTest
private String colors "black", "yellow",
"green", "blue",
"violet", "silver" private String colors2
"gold", "white", "brown",
"blue", "gray", "silver"
22
LinkedList example
public ListTest() LinkedList link
new LinkedList() LinkedList link2 new
LinkedList() for ( int k 0 k lt
colors.length k ) link.add( colors
k ) link2.add( colors2 k )// same
length as colors link.addAll(
link2 ) // concatenate lists
link2 null // release
resources
23
LinkedList example
printList( link ) uppercaseStrings(
link ) printList( link )
System.out.print( "\nDeleting elements 4 to 6..."
) removeItems( link, 4, 7 )
printList( link ) public void
printList( List listRef )
System.out.println( "\nlist " ) for ( int
k 0 k lt listRef.size() k )
System.out.print( listRef.get( k ) " " )
System.out.println()
24
LinkedList example
public void uppercaseStrings( List listRef2 )
ListIterator listIt
listRef2.listIterator() while (
listIt.hasNext() ) Object o
listIt.next() // get item if ( o
instanceof String ) // check for String
listIt.set( ( ( String ) o ).toUpperCase()
) public void removeItems( List
listRef3, int start, int end )
listRef3.subList( start, end ).clear() //
remove items public static void main(
String args ) new ListTest()
25
LinkedList example
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
26
toArray example
import java.util. public class UsingToArray
public UsingToArray() LinkedList
links String colors "black", "blue",
"yellow" 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
27
toArray example
// get the LinkedList elements as an array
colors ( String ) links.toArray( new
String 0 ) System.out.println( "colors
" ) for ( int k 0 k lt colors.length k
) System.out.println( colors k )
public static void main( String args )
new UsingToArray()
28
toArray Example
29
Algorithms
  • Static methods of the Collections class
  • Include sort, binarySearch, reverse, shuffle,
    fill, copy, min and max
  • min and max operate on Collections and the rest
    operate on Lists

30
Sort example
import java.util. public class SortBoth
private static String suits "Hearts",
"Diamonds",
"Clubs", "Spades" public void
printElements() ArrayList theList
new ArrayList( Arrays.asList(
suits ) ) System.out.println( "Unsorted
array elements\n"
theList )
31
Sort example
Collections.sort( theList ) // sort the
List System.out.println( "Sorted array
elements\n" theList
) // sort in descending order
Collections.sort( theList, Collections.reverseOrde
r() ) System.out.println( "Reverse sorted
list elements\n"
theList ) public static void main(
String args ) new SortBoth().printEle
ments()
32
Sort example
Unsorted array elements Hearts, Diamonds,
Clubs, Spades Sorted array elements Clubs,
Diamonds, Hearts, Spades Reverse sorted list
elements Spades, Hearts, Diamonds, Clubs
33
Other Collections Algorithms
static void shuffle(List list) static void
shuffle(List list, Random, rnd) static void
reverse(List l) static void fill(List list,
Object o) static void copy(List dest, List
src) static Object max(Collection coll) static
Object max(Collection coll, Comparator c) static
Object min(Collection coll) static Object
min(Collection coll, Comparator c) static int
binarySearch(List list, Object key) static int
binarySearch(List list, Object key)
34
Set
  • Is a Collection interface
  • Contains unique elements -- no duplicates
  • HashSet -- stores elements in a hash table
  • TreeSet -- stores elements in a tree and they are
    in sorted order

35
Set example
import java.util. public class SetAll
private String colors "red", "white",
"blue", "green",
"gray", "orange",
"tan", "white", "cyan",
"peach", "gray", "orange" public
SetAll() ArrayList aList
36
Set example
aList new ArrayList( Arrays.asList(
colors ) ) System.out.println( "ArrayList
" aList ) System.out.println("HashSet
values---") HashSet ref new HashSet(
aList ) // create a HashSet print( ref
) TreeSet m new TreeSet( Arrays.asList(
colors )) System.out.println("\nTreeSet
values---") print( m )
37
Set example
public void print( Set c ) Iterator i
c.iterator() // get iterator
System.out.println( "Set values are " )
while ( i.hasNext() ) System.out.print(
i.next() " " ) System.out.println()
public static void main( String args )
new SetAll()
38
Set example
ArrayList red, white, blue, green, gray,
orange, tan, white, cyan, peach, gray,
orange HashSet values--- Set values are orange
cyan green tan white blue peach red gray TreeSet
values--- Set values are blue cyan gray green
orange peach red tan white
39
Maps
  • A Map is like a hash table -- keys and values
  • One-to-one mapping -- no duplicate keys
  • HashMap stores keys and elements in a Hashtable,
    unsorted
  • TreeMap stores keys and elements in a tree in
    sorted order (implements SortedMap)

40
MapTest.java
import java.util. public class MapTest
private static String names "one", "two",
"three", "four", "five", "six", "seven",
"two", "ten", "four" // build a HashMap and
output contents public MapTest()
HashMap map new HashMap() Integer i
41
MapTest.java
for ( int count 0 count lt names.length
count ) i ( Integer ) map.get(
new Character( names count .charAt( 0 )
) ) // if key is not in map then give
it value one // otherwise increment its
value by 1 if ( i null )
map.put( new Character( names
count .charAt( 0 ) ), new
Integer( 1 ) ) else
map.put( new Character( names
count .charAt( 0 ) ), new
Integer( i.intValue() 1 ) )
42
MapTest.java
System.out.println( "\nnumber of
words beginning with each letter " )
printMap( map ) // output map contents
public void printMap( Map mapRef )
System.out.println( mapRef.toString() )
System.out.println( "size " mapRef.size() )
System.out.println( "isEmpty "
mapRef.isEmpty() )
// execute application public static void
main( String args ) new MapTest()
// end class MapTest
43
MapTest.java
number of words beginning with each
letter t4, s2, f3, o1 size 4 isEmpty
false
44
Wrappers
  • Static methods of the Collections class that
    return synchronized or unmodifiable
  • Collection
  • List
  • Map
  • Set
  • SortedMap
  • SortedSet

45
Abstract Implementations
  • Programmer can use as framework
  • AbstractCollection
  • AbstractList (random access)
  • AbstractSequentialList
  • AbstractMap
  • AbstractSet
  • Override concrete methods preventing
    modification, if desired

46
Summary
  • Arrays class
  • Collection Interface and Collections class
  • Lists
  • Algorithms
  • Sets
  • Maps
  • Wrappers
  • Abstract Implementations
Write a Comment
User Comments (0)
About PowerShow.com