CoreJava learning 4 -- Set and Map of a Set

Source: Internet
Author: User

1. set

The set does not retrieve elements based on the index. to traverse and combine these elements, you cannot rely on a common for loop.

Only the iterator can be used to traverse a set, and the new loop can be traversed, because the implementation mechanism of the new loop also uses the iterator.

Set common implementation classes:

HashSet: implemented using a hash algorithm

TreeSet: implemented using a binary tree

A specific element cannot be retrieved from the Set. Set cannot be repeated.

Set <String> set = new HashSet <String> ();

Set. add ("one ");

Set. add ("two ");

Set. add ("three ");

// Only the iterator can be used for traversal.

Iterator <String> it = set. iterator ();

While (it. hasNext ()){

String string = it. next ();

System. out. println (string );

}


1. Relationship between HashSet and hashCode Methods


HashSet is the implementation class of the Set interface, which is implemented through a hash table. When adding an object to a HashSet Set, you need to obtain the hashCode value of the object and index it to the corresponding bucket through the hash algorithm.


Specifically: a. when an object is to be inserted into a HashSet, it is preferred to obtain the hashCode value of the object and perform the hash operation to determine the bucket;


B. when using the contains method to determine whether an object is included in a collection, you must first index the object to a specific space based on its hashCode value, and then call the equels method to compare it with the object in the space, this search method is highly efficient than linear table comparison.


When a HashSet is added, it is calculated based on the hashCode value of the element to determine the position of the element. Returns an integer.


Set is also a set. You can also use Comparable.


2. hashCode Method


For objects whose equals method is overwritten, The hashCode method provided by the Object inherited from the hashCode method of the Object class should be properly rewritten to return the integer form of the memory address of the Object ).


Override the hashCode method requires two things: first, the consistency with the equals method, that is, the hashCode method of the two objects whose equals returns true should return the same value; second, the value returned by hashCode must comply with the hash algorithm. Imagine that if many objects return the same hashCode method, the efficiency of the hash table will be greatly reduced. Generally, you can use the tool provided by IDE to automatically generate the hashCode method.


The method provided in the Object. By default, it is an integer that returns the address of the Object.

Note: hashCode () should also be rewritten for classes that overwrite the equals method ().


HashCode rewriting requirements:

1) it is consistent with equals. When equals returns true, the hashCode values of the two objects should also be the same.

2) The hashcode value should be a stable value. The return value of the hashCode () method should not be changed without changing the object content. The object content does not change. It means that the content involved in the equals comparison logic does not change.


The implementation classes of each set support a replication constructor. You can save the elements in a given set to the current set when creating the set.

Note: By using the replication constructor, we only create a new set. For elements, it is not copied!

Public class Demo1_Set {public static void main (String [] args) {Set <Point> s = new HashSet <Point> (); s. add (new Point (1, 2); s. add (new Point (1, 2); s. add (new Point (1, 3); System. out. println (s); // [[x = 1, y = 3], [x = 1, y = 2] // override the hashCode method, so that their equals have the same hashCode. // If the hashCode method is not overwritten, although their equals is true, // but their hashCode returns different, the HashSet will not give the two objects a chance to perform equals comparison.} Class Point {private int x; private int y; public Point (int x, int y) {this. x = x; this. y = y ;}@ Override public int hashCode () {// calculated based on the x y value. If the xy values of the two objects are equal, their hashCode is also equal, obviously conforms to the equals method principles. Final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result ;}@ Override public boolean equals (Object obj) {if (obj instanceof Point) {return (Point) obj ). x = this. x & (Point) obj ). y = this. y ;}return false ;}@ Override public String toString () {return "[x =" + x + ", y =" + y + "]" ;}}


2. Map set

A set defined by Map, also known as a query table, is used to store the so-called "Key-Value" ing pair. Objects used as keys cannot be repeated in the collection.

Map is not a Collection subclass. It is common:

HashMap, implemented using the Hash algorithm.

TreeMap is implemented using binary trees.

1. Common Methods

Methods for accessing elements:

1) V put (K key, Value) stores the value as a key pair to map

Keys cannot be repeated in the entire map, that is, the equala return value of the key-type object cannot be true.

If a duplicate key is used, the value is replaced. The returned value is the value replaced with the same key. If the data is stored for the first time, null is returned.

2) V get (Object key)

Obtain the corresponding value based on the given key. If the key does not exist in the map, null is returned.

3) boolean containsKey (Object key)

Determines whether the set contains the specified key.

3) boolean containsValue (Object value)

Determines whether the set contains the specified value.


Example:

Map <String, Point1> hashmap = new HashMap <String, Point1> (); hashmap. put ("p1", new Point1 (1, 2); hashmap. put ("p2", new Point1 (4, 3); hashmap. put ("p3", new Point1 (1, 2); System. out. println (hashmap); // If duplicate keys are used, the value is replaced. // The returned value is the value replaced with the same key. If the data is stored for the first time, null is returned. System. out. println (hashmap. put ("p3", new Point1 (); // gets the System of the specified key. out. println (hashmap. get ("p3"); // determines whether the set contains the specified key. system. out. println (hashmap. containsKey ("p1"); // determines whether the set contains the specified value. system. out. println (hashmap. containsValue (new Point1 (4, 3 )));

2. Basic principles of HashMap


When a HashMap stores elements, it performs a hash algorithm based on the hashCode value of the key to calculate the location where the key-value group should be stored, if the hashCode value of the key is occupied by an element based on the calculated position, the value will be placed behind that element, because HashMap stores each group of data in the form of a linked list where elements are stored in the same position.

The arrays in HashMap that store data are called hash arrays.

Capacity: The size of the hash array.

Initial Capacity: When a HashMap is created, the size of the hash array is 16 by default.

Size: number of elements stored in hashmap.

Load Factor: according to the experiment, the load factor remains below 0.75, And the hashMap retrieval efficiency is the highest.

Loading Factor = size/Capacity


In view of the principle in which hashmap is stored, the key stored in HashMap must be properly overwritten by the hashCode method.


There are three ways to traverse HashMap:

1) only traverse the key. The keySet is used to obtain a Set.

2) Only traverse the value. values is used to obtain a Collection set. If the set is returned, the element will be lost.

3) Traverse key-value pairs

Example:

Map <String, Point2> map = new HashMap <String, Point2> (); map. put ("p1", new Point2 (2, 2); map. put ("p2", new Point2 (3, 2); map. put ("p3", new Point2 ();/*** keySet () method, returns all the keys in the map in the form of a Set. */Set <String> keySet = map. keySet (); for (String string: keySet) {System. out. print (string + ""); // p3 p2 p1} System. out. println (keySet); // [p3, p2, p1]/*** values () method to obtain all value values in map * The returned value is not a Set, but a list Set. */Collection <Point2> c = map. values (); System. out. println (c); // [[x = 5, y = 6], [x = 3, y = 2], [x = 2, y = 2]/*** Traverse key-value Pair * entrySet (): store the elements in the map to the set with key-value pairs and return the * key-value pair, map is saved using an instance of its internal Entry class. * Entry supports generics. Its generic definition should be consistent with the generic definition of map. */Set <Entry <String, Point2> entries = map. entrySet (); for (Entry <String, Point2> entry: entries) {/*** get the key and value */System through the Entry method. out. println (entry. getKey () + ":" + entry. getValue (); // p3: [x = 5, y = 6] // p2: [x = 3, y = 2] // p1: [x = 2, y = 2]} // or: Iterator <Entry <String, Point2> it = entries. iterator (); while (it. hasNext () {Entry <String, Point2> entry = it. next (); System. out. println (entry. getKey () + ":" + entry. getValue ());}


This article from the "beautiful life needs to carefully record" blog, please be sure to keep this http://huing.blog.51cto.com/1669631/1295018

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.