Framework of Java 2 sets
Set interface: Six interfaces (short dotted line), indicating different set types, is the basis of the set framework.
Abstract class: Five abstract classes (long dotted line) are used to implement part of the set interface. Can be expanded to custom collection classes.
Implementation class: Eight implementation classes (Real-line representation), specific implementation of the interface.
To a large extent, once you understand the interface, you understand the framework. Although you always need to create interface-specific implementations, the methods used to access the actual set should be restricted to the use of interface methods. Therefore, you can change the basic data structure without changing otherCode.
· The collection interface is a set of objects that can be repeated.
· The set interface inherits collections but does not allow repeated operations. It uses an internal arrangement mechanism.
· The list interface inherits collection objects and allows repeated elements to be placed in the order of element insertion without re-arrangement.
· The map interface is a key-value object consisting of a pair, that is, it holds key-value pairs. Duplicate keys are not allowed in map. Has its own internal arrangement mechanism.
· The Element Types in the container are all objects. When getting an element from a container, you must convert it to the original type.
Java 2 simplified set framework
Set Interface
1. Collection Interface
Indicates any object or element group. This interface is used when you want to process a group of elements in a regular way as much as possible.
(1) add or delete a single element:
Boolean add (Object O): adds an object to a set.
Boolean remove (Object O): If the set contains objects that match o, delete the object o
(2) query operations:
Int size (): returns the number of elements in the current set.
Boolean isempty (): determines whether any element exists in the set.
Boolean contains (Object O): searches for whether the set contains object o
Iterator (): returns an iterator used to access each element in the set.
(3) group operation: acts on the element group or the entire set.
Boolean containsall (collection C): checks whether the collection contains all elements in set C.
Boolean addall (collection C): Adds all elements in set C to this set.
Void clear (): deletes all elements in a collection.
Void removeall (collection C): removes all elements in collection C from the collection.
Void retainall (collection C): Removes elements not included in set C from set
(4) convert collection to object array:
Object [] toarray (): returns an array containing all elements of the set.
Object [] toarray (object [] A): returns an array containing all elements of the set. The array and parameter a returned at runtime are of the same type and must be converted to the correct type.
In addition, you can convert a set to any other object array. However, you cannot directly convert a set to an array of the basic data type, because the set must hold objects.
The ITALIC interface method is optional. Because an interface must implement all interface methods and callProgramYou need a way to know if an optional method is not supported. If an unsupportedoperationexception is thrown when an optional method is called, the operation fails because the method is not supported. This exception class inherits the runtimeexception class, avoiding putting all set operations into try-catch blocks ."
Collection does not provide the get () method. To traverse the elements in Collectin, you must use iterator.
1.1.20.actcollection abstract class
The abstractcollection class provides the basic functions of the specific "collection framework" class. Although you can implement all the methods of the collection interface on your own, except that the iterator () and size () methods are implemented in the appropriate subclass, all other methods are implemented by the abstractcollection class. If the subclass does not overwrite some methods, an optional method such as add () will throw an exception.
1.2.iterator Interface
The iterator () method of the collection interface returns an iterator. The iterator interface method can access each element in the collection one by one in an iterative manner, and safely remove appropriate elements from the collection.
(1) Boolean hasnext (): determines whether another element is accessible.
Object next (): returns the next element to be accessed. If the collection ends, a nosuchelementexception exception is thrown.
(2) void remove (): deletes the object returned from the last access. This method must be followed by an element. If the set has been modified after the last access, the method will throw illegalstateexception.
"The deletion operation in iterator also affects the underlying collection ."
The iterator is fail-fast. This means that when another thread modifies the underlying set, if you are using iterator to traverse the set, iterator will throw concurrentmodificationexception (another runtimeexception exception) and immediately fail.
2. List Interface
The list interface inherits the collection interface to define an ordered set that allows repeated items. This interface not only processes part of the list, but also adds location-oriented operations.
(1) location-oriented operations include the ability to insert an element or collection, and the ability to obtain, remove, or change an element. You can search for an element in the list from the header or tail of the list. If an element is found, the position of the report element is as follows:
Void add (INT index, object element): Add an element to the index at the specified position.
Boolean addall (INT index, collection C): Adds all elements of set C to the specified position index.
Object get (INT index): returns the elements at the specified position in the list.
Int indexof (Object O): returns the first position where the element o appears. Otherwise,-1 is returned.
Int lastindexof (Object O): returns the position where the last element o appears. Otherwise,-1 is returned.
Object remove (INT index): deletes elements at a specified position.
Object set (INT index, object element): replaces the element on the Position Index with element, and returns the old element.
(2) The list interface not only traverses the entire list by position sequence iteration, but also can process the subset of the Set:
Listiterator (): returns a list iterator used to access elements in the list.
Listiterator (INT index): returns a list iterator used to access the elements in the list from the specified index.
List sublist (INT fromindex, int toindex): returns the list view of each element from the specified position fromindex (included) to the toindex (not included ).
"Changes to sub-lists (such as add (), remove (), and set () calls) also affect the underlying list ."
2.1.listiterator Interface
The listiterator interface inherits the iterator interface to support adding or modifying elements in the underlying set and bidirectional access. The listiterator does not have the current position, and the cursor is located between the values returned by calling the previous and next methods. A list with a length of N with n + 1 valid index value:
(1) void add (Object O): add the object O to the front of the current location
Void set (Object O): replaces object O with the previous element accessed by the next or previous method. If the list structure is modified after the last call, an illegalstateexception is thrown.
(2) Boolean hasprevious (): determines whether there are elements accessible during backward iteration.
Object previous (): returns the previous object
Int nextindex (): returns the index of the element returned when the next method is called.
Int previusindex (): returns the index of the element returned when the previous method is called the next time.
"Normally, you do not need listiterator to change the direction of elements in a traversal set-forward or backward. Although technically feasible, previous () calls next () immediately and returns the same element. The order of calling next () and previous () is reversed and the result is the same ."
"We need to explain the add () operation a little more. Adding an element will immediately add the new element to the front of the implicit cursor. Therefore, calling previous () after adding an element will return a new element, but calling next () will not work. The next element before the add operation will be returned ."
2.2.abstractlist and abstractsequentiallist abstract classes
There are two abstract List Implementation classes: abstractlist and abstractsequentiallist. Like the abstractset class, they overwrite the equals () and hashcode () methods to ensure that two equal sets return the same hash code. If the two lists are of the same size and contain the same elements in the same order, the two lists are the same. The hashcode () Here is specified in the list interface definition, and implemented here.
Except equals () and hashcode (), abstractlist and abstractsequentiallist implement part of the other list methods. Because Random Access to data and sequential access are implemented separately, it is easier to create a specific list. A set of methods to be defined depends on the behavior you want to support. You never have to provide the Implementation of The iterator method in person.
2.3.Lists and arraylist
There are two common list implementations in the "collection framework": arraylist and sorted list. Which of the two lists is implemented depends on your specific needs. To support random access without inserting or removing elements at any position except the tail, arraylist provides an optional set. However, if you want to frequently add and remove elements from the middle of the list, and as long as the elements in the list are accessed sequentially, the sorted list implementation is better.
"Both arraylist and javaslist implement the cloneable interface and provide two constructor functions, one with no parameters and one with another collection"
2.3.1. Sort list class
The List class adds some methods to process elements at both ends of the list.
(1) void addfirst (Object O): Add object O to the beginning of the List
Void addlast (Object O): adds object O to the end of the list.
(2) object getfirst (): returns the element starting with the list.
Object getlast (): returns the element at the end of the list.
(3) object removefirst (): deletes and returns elements starting with the list.
Object removelast (): delete and return the elements at the end of the list.
(4) construct list (): Create an empty list of links
Collections list (collection C): Creates a list of links and Adds all elements of collection C.
"With these new methods, you can easily treat the consumer list as a stack, queue, or other endpoint-oriented data structure ."
2.3.2. arraylist class
The arraylist class encapsulates an array of dynamically distributed objects. Each arraylist object has a capacity. This capacity indicates the capacity of the array that stores the elements in the list. When an element is added to the arraylist, its capacity is automatically increased within the constant time.
In a program that adds a large number of elements to an arraylist object, you can use the ensurecapacity method to increase capacity. This can reduce the number of reallocation increases.
(1) void ensurecapacity (INT mincapacity): increases the arraylist object capacity by mincapacity.
(2) void trimtosize (): the size of the sorted arraylist object is the current size of the list. The program can use this operation to reduce the arraylist object storage space.
2.3.2.1. randomaccess Interface
A feature interface. This interface does not have any method, but you can use this interface to test whether a set supports valid random access. The arraylist and vector classes are used to implement this interface.
3. Set Interface
The Set interface inherits the collection interface and does not allow repeated items in the set. Each specific set implementation class depends on the equals () method of the added object to check uniqueness. The Set interface does not introduce new methods, so set is a collection, but its behavior is different.
3.1. Hash table
A hash table is a data structure used to find objects. The hash table calculates an integer for each object, which is called a hash code ). A hash table is an array of link lists. Each list is called a buckets (hash table element ). Index = hashcode % buckets (hashcode is the object hash code, and buckets is the total number of hash table elements ).
When you add an element, you may encounter a hash table element that has been filled with the element. This is called hash collisions (hash conflict ). In this case, you must determine whether the element already exists in the hash table.
If the hash code is reasonably randomly distributed and the number of hash table elements is large enough, the number of hash conflicts will be reduced. At the same time, you can set an initial number of hash table elements to better control the operation of the hash table. The initial number of hash table elements is buckets = size * 150% + 1 (size is the expected number of elements ).
If the elements in the hash table are too full, rehashing must be performed ). The hash operation doubles the number of hash table elements and re-imports the original objects into the new hash table elements. The original hash table elements are deleted. Load Factor determines when to re-hash the hash table. In JavaProgramming LanguageThe default value of the loading factor is 0.75, and the default hash table element is 101.
3.2. Comparable interface and comparator Interface
There are two comparison interfaces in the "set framework": the comparable interface and the comparator interface. Java built-in classes such as string and integer implement the comparable interface to provide certain sorting methods, but this method can only be implemented once. For classes that do not implement the comparable interface or custom classes, you can use the comparator interface to define your own comparison methods.
3.2.1. Comparable Interface
In the java. lang Package, the comparable interface is applicable when a class has a natural order. Assuming that the object set is of the same type, this interface allows you to sort the set in a natural order.
(1) int compareto (Object O): compares the current instance object with the object O. If it is before the object O, a negative value is returned. If the two objects are in the same position in the sorting, 0 is returned, if it is behind object O, a positive value is returned.
In Java 2 SDK 1.4, there are twenty-four classes that implement the comparable interface. The following table shows the natural sorting of eight basic types. Although some classes share the same natural sorting, only comparable classes can be sorted.
Class
Sort
Bigdecimal, biginteger, byte, double, float, integer, long, short
Sort by number
Character
Sort by numbers of Unicode values
String
Sort by Unicode values in strings
Using the comparable interface to create the sorting order of your own classes is only a problem of implementing the compareto () method. It usually depends on the natural sorting of several data members. Classes should also overwrite equals () and hashcode () to ensure that two equal objects return the same hash code.