您的位置:首页 > 编程语言 > Java开发

Java tutorial - collections

2015-07-12 16:10 375 查看
Prior to Java 2, Java provided ad hoc classes such as Dictionary,
Vector, Stack, andProperties to
store and manipulate groups of objects. Although these classes were quite useful, they lacked a central, unifying theme. Thus, the way that you used Vector was different from the way that you used Properties.

The collections framework was designed to meet several goals.

The framework had to be high-performance. The implementations for the fundamental collections (dynamic arrays, linked lists, trees, and hashtables) are highly efficient.

The framework had to allow different types of collections to work in a similar manner and with a high degree of interoperability.

Extending and/or adapting a collection had to be easy.

Towards this end, the entire collections framework is designed around a set of standard interfaces. Several standard implementations such as LinkedList,
HashSet, and TreeSet,
of these interfaces are provided that you may use as-is and you may also implement your own collection, if you choose.

A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:

Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.

Implementations, i.e., Classes: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.

Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many
different implementations of the appropriate collection interface.

In addition to collections, the framework defines several map interfaces and classes. Maps store key/value pairs. Although maps are not collections in the proper use of the term, but they are fully integrated with collections.


The Collection Interfaces:

The collections framework defines several interfaces. This section provides an overview of each interface:


Java - The Collection Interface

The Collection interface is the foundation upon which the collections framework is built. It declares the core methods that all collections will have. These methods are summarized in the following table.

Because all collections implement Collection, familiarity with its methods is necessary for a clear understanding of the framework. Several of these methods can throw anUnsupportedOperationException.


Example:

Following is the example to explain few methods from various class implementations of the above collection methods:
List a = new ArrayList();
a.add("Zara");
a.add(new Integer(3));
a.add(new Double(4.5));
System.out.print("ArrayList elements: \n\t" + a + "\n");

List l = new LinkedList();
l.add("Zara");
l.add(new Integer(3));
l.add(new Double(4.5));
System.out.print("LinkedList elements: \n\t" + l + "\n");

Set s = new HashSet();
s.add("Zara");
s.add(new Integer(3));
s.add(new Double(4.5));
System.out.print("HashSet elements: \n\t" + s + "\n");

Map m = new HashMap();
m.put("Zara", "18");
m.put("Mahnaz", 3);
m.put("Ayan", 4.5);
System.out.print("HashMap elements: \n\t" + m + "\n");

The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements.

Elements can be inserted or accessed by their position in the list, using a zero-based index.

A list may contain duplicate elements.

In addition to the methods defined by Collection, List defines some of its own, which are summarized in the following below Table.

Several of the list methods will throw an UnsupportedOperationException if the collection cannot be modified, and a ClassCastException is generated when one object is incompatible with another.

import java.util.*;

public class CollectionsDemo {

public static void main(String[] args) {
List a1 = new ArrayList();
a1.add("Zara");
a1.add("Mahnaz");
a1.add("Ayan");
System.out.println(" ArrayList Elements");
System.out.print("\t" + a1);

List l1 = new LinkedList();
l1.add("Zara");
l1.add("Mahnaz");
l1.add("Ayan");
System.out.println();
System.out.println(" LinkedList Elements");
System.out.print("\t" + l1);
}
}


This would produce the following result:
ArrayList Elements
[Zara, Mahnaz, Ayan]
LinkedList Elements
[Zara, Mahnaz, Ayan]


Java - The Set Interface

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.

The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.
int count[] = {30, 21, 40, 50, 10};
Set<Integer> set = new HashSet<Integer>();
try{
for (int i = 0; i < count.length; ++i)
{
set.add(count[i]);
}
System.out.println(set);
TreeSet<Integer> sortedSet = new TreeSet<Integer>(set);
System.out.println("The sorted set: " + sortedSet);
System.out.println("First element: " + sortedSet.first() + " Last element: " + sortedSet.last());
} catch  (Exception e)
{
System.out.println("Exception.");
}


Java - The SortedSet Interface

The SortedSet interface extends Set and declares the behavior of a set sorted in ascending order. In addition to those methods defined by Set, the SortedSet interface declares the methods summarized in below Table:

Several methods throw a NoSuchElementException when no items are contained in the invoking set. A ClassCastException is thrown when an object is incompatible with the elements in a set.

A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the set.
SortedSet<String> set = new TreeSet<String>();
set.add("a");
set.add("b");
set.add("c");
Iterator<String> it = set.iterator();
while (it.hasNext())
{
Object element = it.next();
System.out.println(element.toString());
}


Java - The Map Interface

The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date.

Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key.

Several methods throw a NoSuchElementException when no items exist in the invoking map.

A ClassCastException is thrown when an object is incompatible with the elements in a map.

A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the map.

An UnsupportedOperationException is thrown when an attempt is made to change an unmodifiable map.

import java.util.*;

public class CollectionsDemo {

public static void main(String[] args) {
Map m1 = new HashMap();
m1.put("Zara", "8");
m1.put("Mahnaz", "31");
m1.put("Ayan", "12");
m1.put("Daisy", "14");
System.out.println();
System.out.println(" Map Elements");
System.out.print("\t" + m1);
}
}


This would produce the following result:
Map Elements
{Mahnaz=31, Ayan=12, Daisy=14, Zara=8}


Java - The SortedMap Interface

The SortedMap interface extends Map. It ensures that the entries are maintained in ascending key order

Several methods throw a NoSuchElementException when no items are in the invoking map. A ClassCastException is thrown when an object is incompatible with the elements in a map. A NullPointerException is thrown if an attempt is made to use a null object when
null is not allowed in the map.


Example:

SortedMap have its implementation in various classes like TreeMap, Following is the example to explain SortedMap functionlaity:
import java.util.*;

public class TreeMapDemo {

public static void main(String args[]) {
// Create a hash map
TreeMap tm = new TreeMap();
// Put elements to the map
tm.put("Zara", new Double(3434.34));
tm.put("Mahnaz", new Double(123.22));
tm.put("Ayan", new Double(1378.00));
tm.put("Daisy", new Double(99.22));
tm.put("Qadir", new Double(-19.08));

// Get a set of the entries
Set set = tm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into Zara's account
double balance = ((Double)tm.get("Zara")).doubleValue();
tm.put("Zara", new Double(balance + 1000));
System.out.println("Zara's new balance: " +
tm.get("Zara"));
}
}


This would produce the following result:
Ayan: 1378.0
Daisy 99.22
Mahnaz: 123.22
Qadir: -19.08
Zara: 3434.34
Zara.s current balance: 4434.34



Java - The Enumeration Interface

The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects.

This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is considered obsolete for new code. However, it is used by several methods defined by the legacy classes such as Vector and Properties, is used by several other API
classes, and is currently in widespread use in application code.


Example:

Following is the example showing usage of Enumeration.
import java.util.Vector;
import java.util.Enumeration;

public class EnumerationTester {

public static void main(String args[]) {
Enumeration days;
Vector dayNames = new Vector();
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();
while (days.hasMoreElements()){
System.out.println(days.nextElement());
}
}
}


This would produce the following result:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday



Java - Generics

The collections framework defines several algorithms that can be applied to collections and maps.

These algorithms are defined as static methods within the Collections class. Several of the methods can throw a ClassCastException, which occurs when an attempt is made to compare incompatible types, or an UnsupportedOperationException,
which occurs when an attempt is made to modify an unmodifiable collection.


Example:

Following example illustrates how we can print array of different type using a single Generic method:
public class GenericMethodTest
{
// generic method printArray
public static < E > void printArray( E[] inputArray )
{
// Display array elements
for ( E element : inputArray ){
System.out.printf( "%s ", element );
}
System.out.println();
}

public static void main( String args[] )
{
// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

System.out.println( "Array integerArray contains:" );
printArray( intArray  ); // pass an Integer array

System.out.println( "\nArray doubleArray contains:" );
printArray( doubleArray ); // pass a Double array

System.out.println( "\nArray characterArray contains:" );
printArray( charArray ); // pass a Character array
}
}


This would produce the following result:
Array integerArray contains:
1 2 3 4 5 6

Array doubleArray contains:
1.1 2.2 3.3 4.4

Array characterArray contains:
H E L L O


Bounded Type Parameters:

There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters
are for.

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound.


Example:

Following example illustrates how extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). This example is Generic method to return the largest of three Comparable objects:
public class MaximumTest
{
// determines the largest of three Comparable objects
public static <T extends Comparable<T>> T maximum(T x, T y, T z)
{
T max = x; // assume x is initially the largest
if ( y.compareTo( max ) > 0 ){
max = y; // y is the largest so far
}
if ( z.compareTo( max ) > 0 ){
max = z; // z is the largest now
}
return max; // returns the largest object
}
public static void main( String args[] )
{
System.out.printf( "Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ) );

System.out.printf( "Maxm of %.1f,%.1f and %.1f is %.1f\n\n",
6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) );

System.out.printf( "Max of %s, %s and %s is %s\n","pear",
"apple", "orange", maximum( "pear", "apple", "orange" ) );
}
}


This would produce the following result:
Maximum of 3, 4 and 5 is 5

Maximum of 6.6, 8.8 and 7.7 is 8.8

Maximum of pear, apple and orange is pear


Generic Classes:

A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.

As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters.


Example:

Following example illustrates how we can define a generic class:
public class Box<T> {

private T t;

public void add(T t) {
this.t = t;
}

public T get() {
return t;
}

public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();

integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));

System.out.printf("Integer Value :%d\n\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());
}
}


This would produce the following result:
Integer Value :10
String Value :Hello World
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: