Java. util Summary 1

Source: Internet
Author: User
Tags addall


Java. util Summary 1
Qzg589 original (Participation score: 123781, expert score: 6302) published: Version: 1.0 read:3141Times

The Java. util package contains some of the most exciting enhancements added in Java 2: class sets. A Class Set
(Collection) is a group of objects. The addition of class sets makes many Java. util members occur in the structure and architecture.
Fundamental changes. It also expands the range of tasks that can be applied to a package. The class set is closely followed by all Java programmers.
The latest technology.
In addition to the class set, java. util also contains various classes and interfaces that support a wide range of functions. These classes and interfaces
It is widely used by core Java packages and can also be used by programs you write. Their applications include
Generate pseudo-random numbers, perform operations on dates and times, observe events, perform operations on pairs, and Mark strings. Because
Java. util has many features, so it is the most widely used Java package.
Java. util contains the following classes. Some newly added in Java 2 are also listed:
Abstractcollection (Java 2) eventobject random
Abstractlist (Java 2) gregoriancalendar resourcebundle
Abstractmap (Java 2) hashmap (Java 2) simpletimezone
Abstractsequentiallist (Java 2) hashset (Java 2) Stack
Abstractset (Java 2) hashtable stringtokenizer
Arraylist (Java 2) worker list (Java 2) timer (Java 2, v1.3)
Arrays (Java 2) listresourcebundle timertask (Java 2, v1.3)
Bitset locale timezone
Calendar observable treemap (Java 2)
Collections (Java 2) properties treeset (Java 2)
Date propertypermission (Java 2) vector
Dictionary propertyresourcebundle weakhashmap (Java 2)
Java. util defines the following interfaces. Note that most of them are newly added in Java 2.
Collection (Java 2) List (Java 2) Observer
Comparator (Java 2) listiterator (Java 2) Set (Java 2)
Enumeration map (Java 2) sortedmap (Java 2)
Eventlistener map. Entry (Java 2) sortedset (Java 2)
Iterator (Java 2)
Resourcebundle class, listresourcebundle class, And propertyresourcebundle class help
Large programs of zone resources are internationalized. The discussion of these classes is described here. Authorized to read/write system attributes
The propertypermission class is beyond the scope of this book. The eventobject and eventlistener classes will be discussed in chapter 20th
Theory. The following describes the remaining classes and interfaces in detail.

Overview of category set 15.1
The Collection framework of Java standardizes the methods your program uses to process object groups. Before Java 2,
Java provides specialized classes such as Dictionary, vector, stack, and properties to store and operate object groups. Do
These classes are very useful, but they lack a centralized and unified topic. Therefore, for example, using the Vector Method
Will be different from the method using properties. Previous specialized methods were not designed to be easy to expand and adapt to new
Environment format. The class set solves these (and other) problems.
The class set framework is designed for a few purposes. First, this framework is of high performance. Basic Class Set (dynamic
Array, chain table, tree, and hash) is efficient. Generally, it is seldom necessary to manually operate these "data engines"
Write code (if any ). Second, the framework must allow different types of class sets to interact in the same way and height.
Operation Method. Third, the class set must be easily extended and/or modified. To achieve this goal, the class set framework
Is designed to contain a set of standard interfaces. Provides several standard implementation tools for these interfaces (for example, using list,
Hashset and treeset), which is usually used in this way. If you want to, you can also implement your own class set.
For convenience, create implementation tools for various special purposes. Some tools can implement your own class set
Easier. Finally, a mechanism is added to allow the fusion of standard arrays into the class set framework.
Algorithms (algorithms) are another important part of the class set mechanism. Algorithm operation class set, which is in the collections class
Is defined as a static method. Therefore, they can be used by all the class sets. Each class set class does not have to implement its own
The algorithm provides a standard method for processing class sets.
The iterator interface is created by the class set framework. An Iteration Program (iterator) provides a multi-purpose
, A standardized method, used for each worker class set of an element. Therefore, the iterator provides an enumeration class set
(Enumerating the contents of a collection) method. Because every class set implements iterator
By using methods defined by iterator, elements of any class of set classes can be accessed. Therefore, make a slight modification and pass through
The program code of the set can also be used to loop through the list.
In addition to the class set, the Framework defines several ing interfaces and classes. Maps stores key/value pairs. Although ing
The correct use of items is not a "Class Set", but they are fully integrated with the class set. In the language of the class set framework, you can
Obtains the ing Class Set "View" (Collection-view ). This "View" contains mappings from the storage in the class set
Element. Therefore, if you select a ing, you can treat it as a class set.
For the original classes defined by Java. util, the Class Set Mechanism is updated so that they can be integrated into the new system. Institute
It is important to understand the following statement: although the increase in the class set changes the structure of many original tool classes, it does not
Will be discarded. The class set only provides a better way to handle things.
Last point: if you are familiar with C ++, you can find that Java's class set technology is similar
The defined standard template library (STL) is similar. In C ++, container is called, while in Java, class set is called.

15.2 class set Interface
The class set framework defines several interfaces. This section provides an overview of each interface. First, we will discuss the reason for the class set Interface
These determine the basic features of the Collection class. The difference is that the specific class only provides different implementations of the standard interface.
Now. The interfaces supporting the class set are summarized in the following table:
Interface Description
Collection allows you to operate on object groups, which are located at the top layer of the class set hierarchy.
List extension collection to process the sequence (Object List)
Set extension collection to process the set. The set must contain unique elements.
Sortedset extends set to process sorted Sets
In addition to the class set interface, the class set also uses the comparator, iterator, and listiterator interfaces. About these interfaces
A more in-depth description will be provided later in this chapter. Simply put, the comparator interface defines how two objects are compared;
Objects in the iterator and listiterator interfaces enumeration class.
To provide maximum flexibility in their use, the class set interface allows you to select some methods. Optional
You can change the content of the class set. Classes that support these methods are called modifiable
(Modifiable ). The class set that cannot be modified is called unmodifiable ). If
When these methods are used, an unsupportedoperationexception is thrown. All
The set of classes can be modified.
The following describes the class set interfaces.
15.2.1 class set Interface
The collection interface is the basis for constructing the class set framework. It declares the core methods that all class sets will possess. These parties
Method is summarized in table 15-1. Because all the class sets implement collection, you are familiar with its methods and have a clear understanding of the box.
Racks are necessary. Several methods may cause an unsupportedoperationexception. As above
As explained, these occur when the class set cannot be modified. When one object is incompatible with another object, for example, when
Attempts to add an incompatible object to a class set. A classcastexception is generated.
Table 15-1 methods defined by collection
Method description
Boolean add (Object OBJ) adds OBJ to the call class set. If obj is added to the class set
Returns true. If obj is already a member of a class set, it cannot be copied.
, False is returned.
Boolean addall (collection C) adds all the elements in C to the call class set. If the operation is successful (also
If the element is added), true is returned; otherwise, false is returned.
Void clear () deletes all elements from the call class set
Boolean contains (Object OBJ) If obj is an element of the call class set, true is returned. Otherwise, false is returned.

Boolean containsall (collection C) If the call class set contains all the elements in C, true is returned; otherwise
False
Boolean equals (Object OBJ) if the call class set is equal to OBJ, true is returned; otherwise, false is returned.
Int hashcode () returns the hash code of the call class set.
Boolean isempty () if the call class set is empty, true is returned; otherwise, false is returned.
Iterator () returns the iterator for calling the class set
Boolean remove (Object OBJ) deletes an instance of OBJ from the call class. If this element is deleted,
True is returned; otherwise, false is returned.
Boolean removeall (collection C) deletes all elements of C from the call class. If the class set is changed (that is
If the element is deleted, true is returned. Otherwise, false is returned.
Boolean retainall (collection C) deletes all elements in the call class except the elements contained in C. For example
If the class set is changed (that is, the element is deleted), true is returned,
Otherwise, false is returned.
Int size () returns the number of elements in the call class set.
Object [] toarray () returns an array containing all the elements stored in the call class set
. An array element is a copy of a collection element.
Object [] toarray (Object array []) returns an array that only contains the types and element types.
Matched class set element. An array element is a copy of a collection element. If Array
The size is equal to the number of matching elements. They are returned to the array. If
The size of an array is smaller than the number of matching elements. An array is allocated and returns a large value.
A small new array. If the array size is greater than the number of matching elements
The Unit after the element of the class set is set to null. If any type of set Element
Is not the child type of the array
Arraystoreexception exception
You can call the add () method to add objects to the class set. Note that add () includes an object-type parameter. Because object
Is the superclass of all classes, so any type of objects can be stored in a class set. However, the original type may not work.
For example, a class set cannot directly store values of the int, Char, or double type. If you want to store these objects
You can use one of the original type wrappers described in Chapter 14th. You can call addall ()
Add all content to another class set.
You can delete an object by calling the remove () method. To delete a group of objects, you can call removeall ()
Method. You can call the retainall () method to delete all elements except a group of specified elements. To clear a class set,
You can call the clear () method.
You can call the contains () method to determine whether a class set contains a specified object. To confirm
You can call the containsall () method. When a class set is empty
You can call the isempty () method for confirmation. Call the size () method to obtain the current element in the class set.
.

The toarray () method returns an array containing elements stored in the call class set. This method is similar
It seems to be more important. It is advantageous to often use the class array syntax to process the content of the class set. In
A path is provided between the class set and the array to take full advantage of the two.
You can call the equals () method to compare whether two class sets are equal. The exact meaning of "equal" can be different from that of the sub-class set.
To the class set. For example, you can run the equals () method to compare the values of elements stored in the class set. In other words,
The equals () method can compare references to elements.
An even more important method is iterator (), which returns an iteration program to the class set. As you will see
In this way, when using a class set framework, iterative programs are crucial for successful programming.
15.2.2 list Interface
The list interface extends collection and declares the features of class sets that store a series of elements. Use a zero-based
Elements can be inserted and accessed through their locations in the list. A list can contain copy elements.
In addition to the methods defined by collection, list also defines some of its own methods. These methods are summarized in
Table 15-2. Note that when the class set cannot be modified, the unsupportedoperation is triggered by several methods.
Exception. When an object is incompatible with another object, for example, when an attempt is made to add an incompatible object to a class
Classcastexception is generated when the set is set.
Table 15-2 methods defined by list
Method description
Void add (INT index, object OBJ) inserts OBJ into the call list. The subscript of the inserted position is transmitted by index. Any existing
In, the elements after the insertion point and after the insertion point are moved forward. Therefore, no RMB
Suru coverage
Boolean addall (INT index, collection C) inserts all the elements in C into the call list. The subscript of the insertion point is transmitted by index.
Delivery. The elements after and after the insertion point are moved forward. Therefore, there are no elements
Is overwritten. If the call list is changed, true is returned; otherwise, false is returned.
Object get (INT index) returns the object stored in the specified subscript in the call class set.
Int indexof (Object OBJ) returns the subscript of the first instance of OBJ in the call list. If obj is not in the list
-1 is returned.
Int lastindexof (Object OBJ) returns the subscript of the last instance of OBJ in the call list. If obj is not a list
-1 is returned.
Listiterator () returns the iterator starting with the call list
Listiterator (INT index) returns the iterator that starts at the specified subscript in the call list.
Object remove (INT index) deletes the element at the index position in the call list and returns the deleted element. After deletion,
The list is compressed. That is to say, the subscript of the element after the deleted element is reduced by one.
Object set (INT index, object OBJ) uses OBJ to assign values to the position specified by index in the call list.
List sublist (INT start, int end) returns a list that includes the call list from start to end? RMB 1
. The elements in the returned list are also referenced by the called object.
For the add () and addall () methods defined by collection, the add (INT, object) and

Addall (INT, collection ). These methods Insert elements at the specified subscript. Add (object) defined by collection)
And addall (Collection) semantics is also changed by list, so that they add elements at the end of the list.
To obtain the objects stored at the specified location, you can use the object subscript to call the get () method. To
If an element is assigned a value, you can call the Set () method to specify the subscript of the object to be changed. Call indexof () or lastindexof ()
You can obtain the subscript of an object.
By calling the sublist () method, you can obtain a sublist of the list that specifies the start subscript and the end submark.
As you can imagine, the sublist () method makes list processing very convenient.
15.2.3 set Interface
The Set interface defines a set. It extends collection and describes the features of class sets that do not allow copying Elements
. Therefore, if you try to add the copied element to the set, the add () method returns false. It is not defined.
Any additional method.
15.2.4 sortedset Interface
The sortedset interface extends the set and describes the features of the Set in ascending order. Except for the methods defined by the set
In addition, the methods described by the sortedset interface are listed in Table 15-3. When no item is included in the call set
Several methods cause nosuchelementexception exceptions. When the object is incompatible with the elements in the call set
Classcastexception exception. If you try to use a null object and the set does not allow null
Nullpointerexception exception.
Table 15-3 methods defined by sortedset
Method description
Comparator comparator () returns the comparison function of the sorted set.
Returns null.
Object first () returns the first element of the sorted set called.
Sortedset headset (Object end) returns a sortedset containing elements smaller than the end.
Include in the called sorted set. The returned elements in the sorted set are also called.
Referenced by the sorted set
Object last () returns the last element of the sorted set called.
Sortedset subset (Object start, object end) returns a sortedset, which includes from start to end? 1. Return class
The elements in the set are also referenced by the called object.
Sortedset tailset (Object start) returns a sortedset that contains values greater
Element equal to start. The elements in the returned set are also referenced by the called object.
Sortedset defines several methods to facilitate the processing of collections. Call the first () method to obtain the set
The first object. Call the last () method to obtain the last element in the set. Call the subset () method,
You can obtain a subset of the sorting set that specifies the first and last objects. If you want to obtain
The headset () method can be used for a subset starting with the first element. To obtain a child at the end of the set
Set. You can use the tailset () method.

15.3 collection class
Now that you are familiar with the class set interface, we will discuss the standard classes to implement them. Some classes provide complete
Can be used. Other classes are abstract and provide the main framework tool as the starting point for creating a specific class set.
No collection class is synchronized, but as you will see later in this chapter, it is possible to get the synchronization version.
The standard collection class is summarized in the following table.
Class description
Abstractcollection implements most collection Interfaces
Abstractlist extends abstractcollection and implements most list interfaces.
Abstractsequentiallist extends abstractlist to be used by the class set. This class set uses continuous instead of random square.
Access its elements
Using list extension abstractsequentiallist to implement chain table
Arraylist uses abstractlist extension to Implement Dynamic Arrays
Abstractset extends abstractcollection and implements most set interfaces.
Hashset extends abstractset to use a hash.
Treeset implements a set stored in the tree. Extended abstractset
Note: In addition to the Collection class, there are several classes left over from previous versions, such as vector and stack.
And hashtable are all redesigned to support the class set form. These contents will be discussed later in this chapter.
The following describes specific collection classes and their usage.
15.3.1 arraylist class
The arraylist class extends javasactlist and executes the list interface. Arraylist supports dynamic numbers that can increase as needed
Group. In Java, standard arrays are fixed. After an array is created, it cannot be extended or shortened.
You must know in advance how many elements an array can hold. However, you will not be able to know how much data is needed until running.
Group. To solve this problem, the class set framework defines the arraylist. In essence, arraylist is
Variable Length array. That is to say, arraylist can dynamically increase or decrease its size. Array list with a raw size
Created. When it exceeds its size, the class set automatically increases. After an object is deleted, the array can be reduced.
Note: dynamic arrays are also supported by vector classes that have been left over from previous versions. For this
This chapter will introduce you later.
Arraylist has the following constructor:
Arraylist ()
Arraylist (collection C)
Arraylist (INT capacity)
The first constructor creates an empty array list. The second constructor creates an array list.
306 Part 1 Java Library
The array list is initialized by elements in class set C. The third constructor creates an array list with the specified
Capacity ). Capacity is the size of the basic array used to store elements. When an element is appended to the array list
The capacity is automatically increased.
The following program shows a simple application of arraylist. First create an array list, and then add the type
String object (recall that a referenced string is converted into a string object ). Then the list is displayed
. After deleting some elements, the list is displayed again.
// Demonstrate arraylist.
ImportJava. util.*;
Class arraylistdemo {
Public static void main (string ARGs []) {
// Create an array list
Arraylist Al = new arraylist ();
System. Out. println ("initial size of Al:" +
Al. Size ());
// Add elements to the array list
Al. Add ("C ");
Al. Add ("");
Al. Add ("e ");
Al. Add ("B ");
Al. Add ("D ");
Al. Add ("F ");
Al. Add (1, "A2 ");
System. Out. println ("size of Al after additions:" +
Al. Size ());
// Display the array list
System. Out. println ("Contents of Al:" + Al );
// Remove elements from the array list
Al. Remove ("F ");
Al. Remove (2 );
System. Out. println ("size of Al after deletions:" +
Al. Size ());
System. Out. println ("Contents of Al:" + Al );
}
}
The program output is as follows:
Initial size of Al: 0
Size of Al after additions: 7
Contents of Al: [C, A2, A, E, B, D, F]
Size of Al after deletions: 5
Contents of Al: [C, A2, E, B, d]
Note that A1 is blank at the beginning. When an element is added, its size increases. When an element is deleted, it is large.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.