Java Learning: Collection Class 2

Source: Internet
Author: User
Tags int size sorts

Set

HashSet

Features: elements are unique, but unordered.

How to ensure the uniqueness of the element (analysis source)?
with simple analysis, we know that the HashSet collection guarantees that the uniqueness of the element is related to the Add () method.
how we want to understand deeply, we must see the Add () method of the source, to see its underlying dependencies on what content?
if (E.hash = = Hash && (k = e.key) = = Key | | key.equals (k)) {...}

Left: E.hash = = Hash
the hash value of the comparison object.
    
Right: ((k = e.key) = = Key | | key.equals (k))
Left: (k = e.key) = = Key
compares the address value of an object.
 
Right: key.equals (k)
compares whether the contents of the object are the same. By default, the address value is compared

Conclusion:
the underlying data structure is a hash table.
hash table relies on two methods: Hashcode () and Equals ()

Execution process:

First, determine if the hash value is the same, and if it is different, add it directly to the collection.
If the same, continue to execute equals (), looking at its return value,
If False, it is added directly to the collection.
If true, the description element is not added repeatedly.


Use:
If you see a collection of hash structures, consider the possible need to override both methods.
If you really want to rewrite it, you can generate it automatically.
The HashSet Practice code is as follows

1 //Create a HashSet collection2Hashset<string> set =NewHashset<string>(); 3         4         //adding elements to the collection5Set.add ("a");6Set.add ("B");7Set.add ("C");8Set.add ("D");9Set.add ("E");TenSet.add ("F"); One          A         //iterating through the collection -         /** - * HashSet Collection features: the * 1. Element unordered - * 2. Element unique -          */ -          for(String string:set) { + System.out.println (string); -}
hashset disorder

TreeSet

Element order: Sorts the elements using the natural order of the elements, or sorts them according to the comparator provided when the set is created.
Depending on the construction method used.

Underlying algorithm: two fork tree.

1treeset<integer> ts =NewTreeset<integer>();2         3         //to store elements in a collection4         //(20,18,23,22,17,24,19,18,24)5Ts.add (20);6Ts.add (18);7Ts.add (23);8Ts.add (22);9Ts.add (17);TenTs.add (24); OneTs.add (19); ATs.add (18); -Ts.add (24); -          the         //iterating through the collection -          for(Integer integer:ts) { - System.out.println (integer); -}
TreeSet Natural Sort

Construction Method:

TreeSet()
Constructs a new empty set that is sorted according to the natural order of its elements.

TreeSet(Comparator<? super E> comparator)

Constructs a new empty TreeSet that is sorted according to the specified comparer.

If you want to sort objects by using a natural sort method, you need to override the CompareTo method in the object class

The overriding method is as follows:

1  Public intCompareTo (Student s) {2         //is to write the rules of comparison of the elements, to be written by yourself3         //Sort by the age of the student4         /**5 * Comparison of two objects:6 * S7 * This8          */9         intnum = This. Age-S.age;Ten         //determine if the age is the same, if the same comparison name One         /** A * Note two points when writing this comparison rule: - * 1. He has the main criteria to sort by the main criteria first - * 2. If the main condition is the same, you need to analyze his secondary conditions, and then to follow the secondary conditions to compare the          */ -          -         intnum2 = num==0? This. Name.compareto (s.name): num; -         returnnum2;
overriding the CompareTo method in the student class

If you sort by using the comparator provided with set, you need to create an implementation class object for the comparator interface.

The cases are as follows:

1treeset<student> ts =NewTreeset<student> (NewComparator<student>() {2              Public intCompare (Student s1, Student S2) {3                 intnum = S1.getage ()-s2.getage ();4                 intnum2 = num==0?s1.getname (). CompareTo (S2.getname ()): num;5                 returnnum2;6             }7         });8         9         //create an object into a collectionTenStudent s =NewStudent ("Guodegang", 50); OneStudent s6 =NewStudent ("Liuyifei", 50); AStudent s2 =NewStudent ("Zhangxueyou", 55); -Student s3 =NewStudent ("Amu", 45); -Student S4 =NewStudent ("Tf-boys", 18); theStudent S5 =NewStudent ("Wangfeng", 49); -          - Ts.add (s); - ts.add (S2); + Ts.add (S3); - Ts.add (S4); + Ts.add (S5); A Ts.add (S6); at          -         //iterating through the collection -          for(Student student:ts) { - System.out.println (student); -}
sort by specified rules

The similarities and differences between HashSet and TreeSet
Same point:
Single-column collection, element not repeatable
Different points:
1. The data structure of the underlying storage is different
The bottom of the hashset is a hashmap hash table structure store, while the TreeSet bottom uses a two-fork tree structure to store
2. Guaranteed data uniqueness on storage
The hashset is guaranteed by the Hashcode () method and the Equals () method, and TreeSet is ensured by the CompareTo () method of the Compareable interface.
3. Not the same order
HashSet Disorderly, TreeSet orderly

Map

The object that maps the key to a value. A map cannot contain duplicate keys, and each key can be mapped to at most one value.

Overview of methods in the map interface (creating a Collection test method):

A: Delete function
void Clear (): Removes all key-value pair elements from the collection
V Remove (Object key): Removes the key value pair element according to the key, and returns the value
B: Judging function
boolean containskey (Object key): Determines whether the specified key is contained in the collection
boolean containsvalue (Object value): Determines whether the specified value is contained in the collection
boolean isEmpty (): Determines whether the collection is empty
C: Get features
set<map.entry<k,v>> EntrySet (): Gets a collection of key-value pairs of objects, traversing the key-value pairs of objects,
use Getkey (), GetValue () to remove keys and values

V get (Object key): Gets the value based on the key
set<k> KeySet (): Get all the keys
collection<v> VALUES (): Get all the values
D: Add features
V put (K key,v value): Set to add a key-value pair
E: Length function
int Size (): The logarithm of key-value pairs.

HashMap
2.1 Element Order: element order is not predictable
2.2 Underlying algorithm: hashing algorithm
2.3 Pair of keys not required (only relative to TreeMap)

The practice code is as follows:

1 //Create student Objects2Student S1 =NewStudent ("Jackson", 60);3Student s2 =NewStudent ("Sun Nan", 50);4Student s3 =NewStudent ("Luv", 30);5Student S4 =NewStudent ("Luv", 30);6         7         //storing objects in a collection8Hm.put (S1, "United States");9Hm.put (S2, "China");TenHm.put (S3, "Korea"); OneHm.put (S4, "China"); A          -         //iterating through the collection -set<student> keys =Hm.keyset (); the          for(Student s:keys) { -System.out.println (s+ "" +Hm.get (s)); -}
HashMap

Java Learning: Collection Class 2

Related Article

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.