Introduction To Java 2 Programming: Array and Collections
Introduction To Java 2 Programming: Array and Collections
Overview
Arrays
Working with arrays Java API support for arrays
Collection classes
Types of collection Working with Collections
Sorting arrays of objects is involves some extra work, as well see later
Java Arrays
Advantages
Very efficient, quick to access and add to Type-safe, can only add items that match the declared type of the array
Disadvantages
Fixed size, some overhead in copying/resizing Cant tell how many items in the array, just how large it was declared to be Limited functionality, need more general functionality
Java Collections
What are they?
A number of pre-packaged implementations of common container classes, such as LinkedLists, Sets, etc. Part of the java.util package.
Advantages
Very flexible, can hold any kind of object
Disadvantages
Not as efficient as arrays (for some uses) Not type-safe. Store references to Object
Java Collections
Two Types of Containers Collections
Group of objects, which may restricted or manipulated in some way E.g. an ordered to make a List or LinkedList E.g. a Set, an unordered group which can only contain one of each item
Maps
Associative array, Dictionary, Lookup Table, Hash A group of name-value pairs
Java Collections
Java Collections
Several implementations associated with each of the basic interfaces Each has its own advantages/disadvantages Maps
HashMap, SortedMap
Lists
ArrayList, LinkedList
Sets
HashSet, SortedSet
Collections
String s = (String)myList.get(1); //get first element String s2 = (String)myList.get(10); //get tenth element
Maps
String s = (String)myMap.get(google); String s2 = (String)mpMap.get(yahoo);
Virtually all require your objects to implement an extra interface, called Comparable
Collections Comparable
The Comparable interface labels objects that can be compared to one another.
Allows sorting algorithms to be written to work on any kind of object so long as they support this interface
Returns
A negative number of parameter is less than the object Zero if theyre equal A positive number if the parameter is greater than the object
Collections Comparator
Like Comparable, but is a stand-alone object used for comparing other objects
Useful when you want to use your criteria, not that of the implementor of the object. Or altering the behaviour of a system
Many of the methods in the Collections object all a Comparator to be specified Again has single method:
public int compare(Object obj1, Object obj2)