Java Collection class learning (6) -- Conclusion

Source: Internet
Author: User
1.6 Summary: Comparison of common classes in the Collection framework

When designing software using a collection framework, it is useful to remember the following hierarchies of the four basic interfaces of the framework:

· The collection interface is a set of objects that can be repeated.

· The set interface inherits collections, but duplicate collections are not allowed.

· The list interface inherits collection, allows repetition, and introduces location subscript.

· The map interface does not inherit set or collection, but accesses key-value pairs.

The following chart describes the differences between implementation classes of common sets:

Collection/Map

Interface

Repetitive members

Order of element storage (ordered/sorted)

Method called in the element

Implemented based on the data structure in that section

Hashset

Set

Unique elements

No order

Equals ()

Hashcode ()

Hash table

Linkedhashset

Set

Unique elements

Insertion order

Equals ()

Hashcode ()

Hash table and two-way linked list

Treeset

Sortedset

Unique elements

Sorted

Equals ()

Compareto ()

Balance Tree)

Arraylist

List

Allowed

Insertion order

Equals ()

Array

Shortlist

List

Allowed

Insertion order

Equals ()

Linked List

Vector

List

Allowed

Insertion order

Equals ()

Array

Hashmap

Map

Unique keys

No order

Equals ()

Hashcode ()

Hash table

Linkedhashmap

Map

Unique keys

Key insertion order/access order of entries

Equals ()

Hashcode ()

Hash table and two-way linked list

Hashtable

Map

Unique keys

No order

Equals ()

Hashcode ()

Hash table

Treemap

Sortedmap

Unique keys

Sorted in key order

Equals ()

Compareto ()

Balance Tree)

2. Exercise

Write a person class to indicate the information of a person. This class has the information of multiple cars, indicating the data of a car that a person can own, and:

Certificate code: ID card object

Name: Name

Cash: Cash

List car; owned cars, which store car objects

Boolean buycar (CAR); buy a car

Boolean sellcar (person P); // sell all your cars to others

Boolean buycar (car, person P); // automatically checks whether the seller P has the car that the buyer wants to buy. If yes, the buyer buys the car and returns true. Otherwise, false is returned.

Viod addcar (CAR); // send a car to the caller of the method.

String tostring (); // obtain the person information.

And write the attributes of the second car class:

String ID; // ID the license plate number.

Cost // price

Color // color

Person owner; // car owner

Tostring (); // get the car information

Equals (); // compare whether the two cars have the same ID.

In another market category, you can buy and sell cars. And keep the information of all trading personnel to a hashmap. We can find the information of corresponding personnel through the ID card number. At the same time, all types of cars are registered in the market, that is, the car information is saved using a set

Attribute:

Hashmap people; // stores the information of the transaction personnel. The key is the ID card number, and the value is the person object.

Method:

Static Boolean sellcar (person P1, car car1, person P2 );

// P1 sells car1 to P2. In this method, the information of benefit persons is recorded in people.

Certificate indicates the ID card:

Attribute:

ID; // number

Method:

Equals (); // compare whether two ID cards are the same. If the IDs are the same, they are considered to be the same.

Hashcode (); // correctly compile the hashcode Method

 

Scenario:

A person named Bob: ID card: 310 in cash: 30000.

There is a car: ID: 001, Red, price: 50000 of the CAR;

A Tom: ID card: 210 in cash: 70000,

There is a car: Color: white, ID: 003, price: 25000.

A man named King: ID card: 245 cash: 60000,

There are two cars: Color: white, ID: 005, price: 18000.

Color: Red, ID: 045, price: 58000.

 

Tom bought Bob's car. He owns two cars.

King bought Bob the car with ID = 005.

What is the final information of each person?

3 appendix: Sorting

In order to add the sorting support to Java 2 SDK and version 1.2 with the additional part of the "collection framework", the core Java library has made many changes. For the string and integer classes, the comparable interface is now implemented to provide a natural sorting order. You can implement the comparator interface to define your own classes that have no natural order, or when you want a sequence that is different from the natural order.

To use the sorting function, the collection framework provides two interfaces to use this function: sortedset and sortedmap.

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.

The compareto () method compares the current instance with the elements passed in as parameters. If the current instance appears before the parameter during sorting, a negative value is returned. If the current instance appears after the parameter, a positive value is returned. Otherwise, zero is returned. Here, the zero return value is not required to indicate that the elements are equal. The zero return value indicates that two objects are in the same position.

In Java 2 SDK, there are fourteen classes in version 1.2 that implement the comparable interface. The following table shows their natural sorting. 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

Collationkey

Sort by language-sensitive strings

Date

Sort by generation

File

Sort by Unicode values of fully qualified characters of the system-specific path name

Objectstreamfield

Sort by Unicode values of Characters in the name

String

Sort by Unicode values in strings

Creating your own class comparable is just a problem of implementing the compareto () method. It usually depends on the natural sorting of several data members. Your own classes should also overwrite equals () and hashcode () to ensure that two equal objects return the same hash code.

Comparator Interface

If a class cannot be used to implement java. Lang. Comparable, You can provide your own Java. util. comparator behavior. If you do not like the default comparable behavior, you can provide your own comparator.

The Return Value of the comparator compare () method is similar to that of the compareto () method of comparable. In this case, if the first element appears before the second element during sorting, a negative value is returned. If the first element appears, a positive value is returned. Otherwise, zero is returned. Similar to comparable, the zero return value does not indicate equal elements. A zero return value indicates that two objects are in the same position. The comparator user determines how to handle the problem. If the result of comparing two unequal elements is zero, you should first make sure that it is the result you want and then record the behavior.

For demonstration, you will find that writing a new comparator that ignores case sensitivity is easier than using collator for language-specific and case-insensitive comparison. Such an implementation is as follows:

Class caseinsensitivecomparator implements comparator {

Public int compare (Object element1, object element2 ){

String lowere1 = (string) element1). tolowercase ();

String lowere2 = (string) element2). tolowercase ();

Return lowere1.compareto (lowere2 );

}

}

Because each class has an object subclass in some places, this is not a necessary condition for implementing the equals () method. In fact, you will not do this in most cases. Remember that the equals () method checks the equality implemented by comparator, not the objects in the comparison state.

The collections class has a predefined comparator for reuse. Call collections. reverseorder () to return a comparator, which sorts objects that implement the comparable interface in reverse order.

PDF documentation needed can be downloaded here: http://download.csdn.net/detail/my_session/4555903

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.