Java study note 11 -- Summary of the set and java study note 11 --

Source: Internet
Author: User

Java study note 11 -- Summary of the set and java study note 11 --

Java learning notes series:

Java Study Notes 10-generic Summary

Java study notes 9-internal class Summary

Java study note 8-interface Summary

Java study notes 7 -- abstract classes and abstract methods

Java study Note 6-class inheritance, Object class

Java study notes 5-Class Method

Java study note 4-object initialization and collection

Java Study Notes 3-Basics of classes and objects

Java study Note 2 -- data type, array

Java study Note 1-Summary of the development environment Platform

URL: http://www.cnblogs.com/archimedes/p/java-study-note11.html.

Java Collection framework Overview

A set is to combine several similar "data" with the same usage into a whole.

There are three types of collection systems:

(1) List: the List set distinguishes the order of elements and allows the same element to be included.

(2) Set: Set sets do not distinguish the order of elements, and cannot contain the same elements.

(3) Map: the "key"-"value" pair stored in the Map set. The "key" cannot be repeated, and a "key" can only correspond to one "value ".

Only the referenced data type can be saved in the Java Collection, that is, the object address is saved, not the object itself. The element in the collection is equivalent to a variable of the reference type.

All the container APIs provided by JDK are in the java. util package.

Java collections mainly include three types: Set, List, and Map ).

Java Collection class diagram:

Collection and Iterator Interfaces

The Collection interface declares the general methods applicable to Java collections (including Set and List only. Therefore, the Set and List objects can call the preceding methods, but the Map objects cannot.

The Iterator interface hides the data structure of the underlying set and provides a unified interface for the customer program to traverse various data sets.

If the elements in the set are not sorted, The Iterator traverses the order of elements in the Set, which is not necessarily the same as the order in which the elements are added to the set.

Methods In the Collection interface:

Boolean add (E o) Make sure that this collection contains the specified elements (optional)
Void clear () Remove all elements from this collection (optional)
Boolean contains (Object o) Returns true if the collection contains the specified element.
Boolean isEmpty () Returns true if the collection does not contain elements.
Iterator <E> iterator () Returns the iterator that iterates over the elements of this collection.
Boolean remove (Object o) Remove a single instance of the specified element from this collection. If yes (optional)
Int size () Returns the number of elements in the collection.
Object [] toArray () Returns an array containing all elements in the collection.

Example of the Collection method:

Public class javatest {public static void main (String args []) {Collection c = new ArrayList (); c. add ("Hello World! "); // Add a String type object c. add (new Integer (100); // add an Integer type object c. add (new Float (2323.45f); // add a Float type object System. out. println (c. size (); System. out. println (c );}}
List interface and implementation class

List is a Collection sub-interface. objects stored in containers that implement the List interface are ordered and can be repeated. The objects stored in the List container all have an integer serial number, which records the position of the object in the container and can access the elements in the container according to the serial number.

JDK provides the ArrayList and listlist classes to implement the List interface. The related methods are as follows:

Object get(int index)Object set(int index,Object obj)void add(int index,Object obj)Object remove(int index)int indexOf(Object obj)int lastIndexOf(Object obj)

List interface Example:

public class javatest {      public static void main(String args[]) {         List li=new ArrayList();        for(int i=0;i<10;i++)            li.add("a"+i);        System.out.println(li);        li.add(3,"a20");        System.out.println(li);        li.set(4,"a30");        System.out.println(li);        System.out.println((String)li.get(2));        li.remove(0);        System.out.println(li);   }}

The running result is as follows:

[A0, a1, a2, a3, a4, a5, a6, a7, a8, a9]
[A0, a1, a2, a20, a3, a4, a5, a6, a7, a8, a9]
[A0, a1, a2, a20, a30, a4, a5, a6, a7, a8, a9]
A2
[A1, a2, a20, a30, a4, a5, a6, a7, a8, a9]

Implementation class of the List interface-ArrayList

Java. util. ArrayList implements the List interface to describe the List of variable-length arrays (array-based underlying implementation ). ArrayList allows the element value to be null and provides some new methods to operate on the size of the list.

public ArrayList()public ArrayList(int initialCapacity)public void ensureCapacity(int minCapacity)public void trimToSize()

ArrayList example:

ArrayList list=new ArrayList(6);list.add("codingwu");list.add(new Integer(10));list.add(new Double(10.5));        System.out.println(list.size());Object item[]=list.toArray();for(int i=0;i<item.length;i++)    System.out.println(item[i]);list.trimToSize();     

Implementation class of the List interface-Vector

Java. util. Vector implements the List interface, which is used to describe variable-length array vectors (the underlying layer uses arrays ).

Difference from ArrayList: Vector is thread-safe (synchronous) and is used in multi-threaded environments, resulting in slow running efficiency. ArrayList is NOT thread-safe and is used in a single-threaded environment.

Add a method to the Vector class:

public Vector()public Object elementAt(int index)public void removeElement(int index)public void insertElement(Object obj,int index)public boolean removeElement(Object obj)public void removeAllElements()public Object toArray()
Map interface and implementation class

This interface is the root collection class used to store element pairs of "key" and "value". Each keyword is mapped to a value, when you need to use keywords to achieve quick access to values

The abstract methods of declarations mainly include:

Query and modification methods

Two main implementation classes:

HashTable and HashMap

Query Method

Int size () -- returns the number of elements in the Map.

Boolean isEmpty () -- returns whether the Map contains elements. If no element is included, true is returned.

Boolean containsKey (Object key) -- determines whether a given parameter is a key in Map)

Boolean containsValue (Object val) -- determines whether a given parameter is a value in Map)

Object get (Object key) -- returns the value associated with the given keyword in the Map)

Collection values () -- returns the Collection object that contains all values in the Map.

Set keySet () -- returns the Set object containing all the keywords (KEYS) in the Map.

Set entrySet () -- returns the Set object that contains all items in the Map.

Modification Method

Object put (Object key, Object val) -- adds the given key/value pair to the Map Object. The key must be unique. Otherwise, the new value will replace the existing value in the Map object.

Void putAll (Map m) -- adds all the items in the given Map parameter to the Map object of the receiver.

Object remove (Object key) -- deletes an item with a specified keyword from the Map Object.

Void clear () -- delete all items from the Map object

Hash table

Also called a hash list, it is a collection class structure used to store group objects. The two common classes are HashTable and HashMap.

The way in which the hash table stores objects is different from the array, Vector, and ArrayList mentioned above. The storage locations of objects in arrays, vectors, and ArrayList are random, that is, there is no necessary link between the objects themselves and their storage locations. Therefore, when an object is searched, it can only be compared with each element in a certain order (such as sequential search and binary search). If the number of elements in an array or vector is large, the search efficiency will inevitably decrease.

In a Hash table, the storage location of an object and key attribute k of the object have a specific ing relationship f, which is called the Hash function. It allows each object to correspond to a unique storage location. Therefore, when searching, you only need to calculate the value of f (k) based on the key attribute k of the object to be queried to know its storage location.

Hash Table related concepts:

Capacity-the capacity of the hash table is not fixed. As the object is added, its capacity can be automatically expanded.

Keyword/key-each stored object requires a keyword key, which can be the object itself or a part of the object (such as an attribute of the object)

Hash code (hash code)-to store an object to HashTable, You need to map its key keyword to an integer data, called the key hash code)

Hash function: returns the hash code of an object.

Item (item)-each item in the hash table has two fields: key of the keyword field and value of the value Field (that is, the stored object ). Both key and value can be any Object type, but cannot be null. All keywords in HashTable are unique.

Load factor-(number of items in the table)/(Table capacity)

Constructor:
Hashtable (); // The initial capacity is 101, and the maximum filling factor is 0.75 Hashtable (int capacity); Hashtable (int capacity, float maxLoadFactor );

Object put (Object key, Object value) -- value is added to the hash table with key as its keyword. If this keyword does not exist in the table, null is returned; otherwise, the value stored in the table

Hashtable aPhoneBook = new Hashtable (); aPhoneBook. put ("Zhang Lei", "010-84256712"); aPhoneBook. put ("Zhu Yongqin", "010-82957788"); aPhoneBook. put ("Liu Na", "010-80791234"); System. out. println (aPhoneBook); // display {Liu Na = 010-80791234, Zhu Yongqin = 010-82957788, Zhang Lei = 010-84256712}View Code

Object get (Object key) -- returns the value of the key keyword. If no value exists, null is returned. For example

Hashtable aPhoneBook = new Hashtable (); aPhoneBook. put ("Zhang Lei", "010-84256712"); aPhoneBook. put ("Zhu Yongqin", "010-82957788"); aPhoneBook. get ("Zhang Lei"); // return "010-84256712" aPhoneBook. get ("Zhu Yongqin"); // return "010-82957788" aPhoneBook. get ("Liu Ling"); // return nullView Code

Object remove (Object key) -- removes key/value pairs from the table and returns the value removed from the table. If no key/value pair exists, null is returned. For example

Hashtable aPhoneBook = new Hashtable (); aPhoneBook. put ("Zhu Yongqin", "010-82957788"); aPhoneBook. put ("Liu Na", "010-80791234"); aPhoneBook. remove ("Zhu Yongqin"); aPhoneBook. remove ("010-80791234"); // No error, but nullSystem is returned. out. println (aPhoneBook); // display {Liu Na = 010-80791234}View Code
Boolean isEmpty () -- determines whether the hash table is empty boolean containsKey (Object key) -- determines whether the given keyword is in the boolean contains (Object value) of the hash table) -- determine whether the given value is in the boolean containsValue (Object value) in the hash table -- determine whether the given value is in the void clear () in the hash table -- clear the hash table Enumeration elements () -- returns the Enumeration object Enumeration keys () containing the value -- returns the Enumeration object containing the keyword.

The HashMap class is similar to the HashTable class, but the HashTable class does not allow empty keywords, while the HashMap class does.

Set interface and implementation class

Set is the simplest Set. Objects in the Set are not sorted in a specific way and there are no repeated objects. The Set interface mainly has two implementation classes: HashSet and TreeSet.

There is no obvious order between multiple objects in the Set, basically the same as the Collection method. But the behavior is different (Set cannot contain duplicate elements ). The Set does not allow repeated elements because Set judges that two objects are the same instead of using the = Operator, but based on the equals method. Returns true if two objects are compared using the equals method.

Public class TestSet {public static void main (String [] args) {Set <String> books = new HashSet <String> (); // Add a String object books. add (new String ("Struts2 authoritative guide"); // add another String object. // The addition fails because the two String objects are equal through the equals method, returns false boolean result = books. add (new String ("Struts2 authoritative guide"); System. out. println (result); // The output below shows that the set has only one element, System. out. println (books );}}

Program running result:

False
[Struts2 authoritative guide]

Note: In the program, the string object added twice in the book set is obviously not an object (the program creates a String object using the new keyword). When the = Operator is used, false is returned, if the equals method is used for comparison, true is returned. Therefore, you cannot add it to the Set. Only one element can be output at the end. The knowledge in the Set interface is also applicable to three implementation classes: HashSet, TreeSet, and EnumSet.

HashSet class

HashSet stores the elements of a set based on the Hash algorithm, so it has good access and search performance.

HashSet features:

(1) HashSet is not synchronous. To access multiple threads, you must use the code to ensure synchronization.

(2) The set element value can be null.

The HashSet sets judge that two elements are equal. The two objects are equal through the equals method, and the hashCode () method return values of the two objects are equal.

// The equals method of class A always returns true, but does not overwrite its hashCode () method class A {public boolean equals (Object obj) {return true ;}} // The hashCode () method of class B always returns 1, but does not overwrite its equals () method class B {public int hashCode () {return 1 ;}} // The hashCode () method of class C always returns 2, but does not overwrite its equals () method class C {public int hashCode () {return 2 ;} public boolean equals (Object obj) {return true;} public class TestHashSet {public static void main (String [] args) {HashSet <Object> books = new HashSet <Object> (); // Add two A objects, two B objects, and two C objects to the books set respectively. books. add (new A (); books. add (new A (); books. add (new B (); books. add (new B (); books. add (new C (); books. add (new C (); System. out. println (books );}}

Program running result:

[B @ 1, B @ 1, C @ 2, A @ b5dac4, A @ 9945ce]

TreeSet class

TreeSet is the only implementation of the SortedSet interface. TreeSet can ensure that the elements in the set are sorted (the elements are ordered ).

TreeSet provides several additional methods:

Comparator comparttor (): returns the Compara input used by the current Set, or returns null, indicating that the Comparator is naturally sorted.

Object first (): returns the first element in the set.

Object last (): returns the last element in the set.

Objiect lower (Object e): return the elements in the set that are located before the specified Element (that is, elements smaller than the maximum element of the specified element, the reference element can be not a TreeSet element ).

Object higher (Object e): returns the elements located after the specified Element in the collection (that is, the minimum element greater than the specified element. The reference element does not need the TreeSet element ).

SortedSet subSet (fromElement, toElement): returns a subSet of this Set, ranging from fromElement (including greater than or equal to) to toElement (excluding less ).

SortedSet headSet (toElement): returns a subset of this Set, which consists of elements smaller than toElement.

SortedSet tailSet (fromElement): returns a subset of this Set, which consists of elements greater than or equal to fromElement.

Public class TestTreeSetCommon {public static void main (String [] args) {TreeSet <Integer> nums = new TreeSet <Integer> (); // Add four Integer objects nums to the TreeSet. add (5); nums. add (2); nums. add (10); nums. add (-9); // output the set element. The set element is in the order state System. out. println (nums); // the first element of the output set, System. out. println (nums. first (); // output the last element System in the set. out. println (nums. last (); // returns a subset smaller than 4, excluding 4 systems. out. println (nums. headSet (4 ));/ /Returns a subset greater than 5. If Set contains 5, the child Set also contains 5 systems. out. println (nums. tailSet (5); // returns a subset greater than or equal to-3 and less than 4. System. out. println (nums. subSet (-3, 4 ));}}

Note: As can be seen from the running results, TreeSet is not sorted by element insertion order, but by element actual value. TreeSet uses the data structure of the red/black tree to sort elements. The specific sorting content will be described in subsequent articles.

References

Http://www.cnblogs.com/zhxxcq/archive/2012/03/14/2395511.html

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.