Java programming-sun Xin Java no difficulty lesson8 collection class

Source: Internet
Author: User
Tags comparable sorts
Java programming -- Sun Xin Java is not difficult lesson8 collection class

Highlights of this section:Collection class operations and features (
For more information about data structure, see the data structure teaching material. This part of knowledge has a wealth of theories and is omitted here)
Details:

1. interfaces in the Collection framework
Collection: The Root Interface in the collection hierarchy. JDK does not provide a direct implementation class for this interface.
Set: duplicate elements cannot be contained. Sortedset is a set that sorts elements in ascending order.
List: an ordered set that can contain repeated elements. Supports index-based access.

Map: contains the key-value pair. Map cannot contain duplicate keys.

Sortedmap is a map that sorts keys in ascending order.

Shows the interfaces in the Collection framework:

2. Implementation classes in the Collection framework

Shows the implementation classes in the Collection framework in a neat hierarchy:


(1)Arraylist and rule list
Arraylist:
We can regard arraylist as an array that can automatically increase the capacity.
Returns an array using the toarray () of arraylist.
Arrays. aslist () returns a list.
Iterator provides a common way to access elements in a set.
Shortlist:
A two-way cyclic list is implemented.
Use consumer list to implement stack, queue, and double-ended queue ).

The stack test code based on consumer list is as follows:

// Stack test Import Java based on consumer list. util. *; Class mystack {private writable list LL = new writable list (); Public void push (Object O) {ll. addfirst (o);} public object POP () {return ll. removefirst ();} public object PEEK () {return ll. peekfirst ();} public Boolean empty () {return ll. isempty ();} public static void main (string [] ARGs) {mystack MS = new mystack (); Ms. push ("one"); Ms. push ("two"); Ms. push ("three"); system. out. println (Ms. pop (); system. out. println (Ms. peek (); system. out. println (Ms. pop (); system. out. println (Ms. empty (); // running result/* Three Two two false */}}

The queue test code based on the queue list is as follows:

// Import Java. util. *; Class myqueue {private writable list LL = new writable list (); Public void put (Object O) {ll. add (o);} public object get () {return ll. removefirst ();} public Boolean empty () {return ll. isempty ();} public static void main (string [] ARGs) {myqueue MQ = new myqueue (); MQ. put ("one"); MQ. put ("two"); MQ. put ("three"); system. out. println (MQ. get (); system. out. println (MQ. get (); system. out. println (MQ. get (); system. out. println (MQ. empty (); // running result/* One Two Three true */}}

(2)Collections class
Sort: collections. Sort ()
(1) Natural ordering; (2) Implement the comparator interface.
Take the largest and smallest elements: collections. Max (), collections. Min ().
Search for the specified Element in the sorted list: collectons. binarysearch ().
The test code for natural sorting, comparator interface implementation, and iterator is as follows:

Import Java. util. *; Class arraylisttest {// iteration output element public static void printelements (Collection e) {iterator iter = E. iterator (); While (ITER. hasnext () {system. out. println (ITER. next () ;}} public static void main (string [] ARGs) {/* // basic test arraylist Al = new arraylist (); Al. add ("Java"); Al. add ("arraylist"); Al. add ("test"); For (INT I = 0; I <Al. size (); I ++) system. out. println (Al. get (I); system. out. println (L); // [Java, arraylist, test] Call the tostring method of arraylist * // collection. toarray and arrays. aslist conversion test arraylist Al = new arraylist (); Al. add ("Java"); Al. add ("arraylist"); Al. add ("test"); object [] objs = Al. toarray (); // convert the list to an array for (INT I = 0; I <objs. length; I ++) system. out. println (objs [I]); List ls = arrays. aslist (objs); // array converted to list aslist returns a fixed-size (a fixed-size) List of printelements (LS); // ls. add ("add"); // error. unsupport Edoperationexception due to fixed size * // iterator makes Test 1 arraylist Al = new arraylist (); Al. add ("Java"); Al. add ("arraylist"); Al. add ("test"); object [] objs = Al. toarray (); List ls = arrays. aslist (objs); // aslist returns a fixed-size (a fixed-size) List // iterator iter = Al. iterator (); // iterator ITER of arraylist = ls. iterator (); // The list iterator does not support the remove method because the size of ITER is fixed. next (); // ITER. remove (); // before deletion, an element while (ITER. hasnext () {System. Out. println (ITER. next ();} * // iterator Test 2 list ls = new arraylist (); LS. add ("Java"); LS. add ("arraylist"); LS. add ("test"); iterator iter = ls. iterator (); // list iterator now supports the remove method because there is no fixed size ITER. next (); ITER. remove (); While (ITER. hasnext () {system. out. println (ITER. next ();} * // sort test code student stu1 = new student (3, "zhangsan"); Student stu2 = new student (1, "Lisi"); Student stu3 = new student (2, "zhaoer"); s Tudent stu4 = new student (2, "wangwu"); arraylist Al = new arraylist (); Al. add (stu1); Al. add (stu2); Al. add (stu3); Al. add (stu4); * // collections. sort (Al ); // The comparable interface must be implemented in ascending order of the natural order // The running result of the natural Sorting/* num = 1 name = Lisi num = 2 name = zhaoer num = 2 name = wangwu num = 3 name = zhangsan * // collections. sort (Al, new student. studentcomparator (); // sort by specified comparator. The comparator interface must be implemented. // specify the comparator sorting result./* num = 1 name = Lisi num = 2 name = wangwu num = 2 name = zhaoer num = 3 name = zhangsan * // collections. sort (Al, collections. reverseorder ()); // The Reverse sorting reverseorder method returns a comparator // The Reverse sorting result/* num = 3 name = zhangsan num = 2 name = zhaoer num = 2 name = wangwu num = 1 name = Lisi * /// printelements (Al ); // iteration output element} class student implements comparable {int num; string name; // use the internal class to implement the comparator interface static class studentcomparator implements comparator {publi C int compare (Object O1, object O2) {student stu1 = (student) O1; Student stu2 = (student) O2; int ret = stu1.num> stu2.num? 1 :( stu1.num = stu2.num? 0:-1); If (ret = 0) ret = stu1.name. compareto (stu2.name); return ret;} // Note: The equals method inherits from the object class, so you do not need to implement the equals method} student (INT num, string name) {This. num = num; this. name = Name;} // implement the comparable interface public int compareto (Object O) {student Stu = (student) O; return this. num> Stu. num? 1 :( this. num = Stu. Num? 0:-1);} Public String tostring () {return "num =" + num + "" + "name =" + name ;}}

(3)Hashset and hashmap
Hashset: implements the hash table of the Set interface, which is implemented by hashmap. We should define hashcode () and equals () for each object to be stored in the hash table ().
Hashmap:
Hashmap hashes keys.

Keyset (), values (), entryset ().

The test code for hashset and hashmap is as follows:

// Hashset test code import Java. util. *; Class hashsettest {public static void main (string [] ARGs) {/* // basic test hashset HS = new hashset (); HS. add ("one"); HS. add ("two"); HS. add ("three"); HS. add ("four"); HS. add ("one"); // duplicate elements cannot be saved. iterator iter = HS. iterator (); While (ITER. hasnext () system. out. println (ITER. next (); * // test the hashcode calculation method to implement hashset HS = new hashset (); HS. add (new student (1, "zhangsan"); HS. add (new student (2, "Lisi"); HS. add (new student (3, "wangwu ")); // Calculate New Based on Object hash code to generate different objects // Therefore, hashset considers two different objects to store two objects, although they are duplicate HS. add (new student (1, "zhangsan"); iterator iter = HS. iterator (); While (ITER. hasnext () system. out. println (ITER. next ()); // run the result when the hascode and equals methods of the student class are not implemented/* num = 2 Name Lisi num = 1 Name zhangsan num = 1 Name zhangsan num = 3 name wangwu */// run the result in the hascode and equals methods of the Student Class/* num = 2 Name Lisi num = 1 Name zhangsan num = 3 name wangwu */} class student {int num; string name; student (INT num, string name) {This. num = num; this. name = Name;} // The hashcode and equals methods must be overwritten by the Public int hashcode () {return num * (name. hashcode ();} public Boolean equals (Object O) {student Stu = (student) O; return this. num = Stu. num & this. name. equals (Stu. name) ;}public string tostring () {return "num =" + num + "" + "name" + "" + name ;}}
// Hashmap test code import Java. util. *; Class hashmaptest {public static void printelements (Collection e) {iterator iter = E. iterator (); While (ITER. hasnext () {system. out. println (ITER. next () ;}} public static void main (string [] ARGs) {hashmap Hm = new hashmap (); HM. put (1, "zhangsan"); HM. put (2, "Lisi"); HM. put (3, "wangwu"); // obtain the key value system by the key. out. println ("values getted from key:"); system. out. println (HM. get (1); system. out. println (HM. get (2); system. out. println (HM. get (3); // obtain the key view set Keys = HM. keyset (); system. out. println ("keys view:"); printelements (KEYS); // gets the value view collection values = HM. values (); system. out. println ("values view:"); printelements (values); // obtain the key-value pair set entries = HM. entryset (); system. out. println ("entries:"); printelements (entries); // iteration entries iterator iter = entries. iterator (); system. out. println ("keys and values in entries:"); While (ITER. hasnext () {map. entry en = (map. entry) ITER. next (); system. out. println (en. getkey () + ":" + en. getvalue ();}/* // run the result values getted from key: zhangsan Lisi wangwu keys view: 1 2 3 values view: zhangsan Lisi wangwu entries: 1 = zhangsan 2 = Lisi 3 = wangwu keys and values in entries: 1: zhangsan 2: Lisi 3: wangwu */}}

(4)Treeset and treemap
Treeset:
Treeset is implemented by treemap.
Treeset is an ordered set. The elements in the treeset are arranged in ascending order. By default, the elements in the treeset are arranged in natural order. This means that the comparable interface must be implemented for the elements in the treeset.
When constructing a treeset object, we can pass the comparator object that implements the comparator interface.
Treemap: The treemap is sorted by key.

The treeset test code is as follows:

// Treeset test code import Java. util. *; Class treesettest {public static void main (string [] ARGs) {/* // use treeset Ts = new treeset (); Ts. add ("Java"); Ts. add ("treeset"); Ts. add ("test"); iterator iter = ts. iterator (); While (ITER. hasnext () system. out. println (ITER. next (); * // The treeset Ts = new treeset (new student. studentcomparator (); Ts. add (new student (3, "zhangsan"); Ts. add (new student (1, "Li Si "); Ts. add (new student (2, "zhaoer"); Ts. add (new student (2, "wangwu"); iterator iter = ts. iterator (); While (ITER. hasnext () system. out. println (ITER. next () ;}} class student {int num; string name; // implement the comparator static class studentcomparator implements comparator {public int compare (Object O1, object O2) {student stu1 = (student) O1; Student stu2 = (student) O2; int ret = stu1.num> stu2.num? 1 :( stu1.num = stu2.num? 0:-1); If (ret = 0) ret = stu1.name. compareto (stu2.name); return ret;} // The equals method is inherited from the object class, so you do not need to implement this method} student (INT num, string name) {This. num = num; this. name = Name;} Public String tostring () {return "num =" + num + "" + "name =" + name ;}}

(5)Comparison of several types
Comparison between arraylist and rule list:
The arraylist uses arrays at the underlying layer, while the sorted list is completed by a general double-linked list. Each object in the list has two references besides the data itself, it refers to the first element and the last element respectively.
If we often add elements at the beginning of the list or insert or delete elements in the list, we should use the sort list. Otherwise, using arraylist will be faster.
Comparison between hashset and treeset:
Hashset is implemented based on the hash algorithm, and its performance is generally better than treeset. We usually should use hashset. We only use treeset when we need the sorting function.
Comparison between hashmap and treemap:
Similar to set, hashmap is generally faster than treemap, and treemap is used only when sorting is required.
3. properties class
Shows how to create a configuration file:

The test code for creating a proptest is as follows:

// Properties Test code import Java. util. *; import Java. io. *; Class proptest {public static void main (string [] ARGs) {/* // obtain the current system property // properties prop = system. getproperties (); // prop. list (system. out); * // read ini configuration file information properties PPS = new properties (); try {PPS. load (New fileinputstream ("propini. ini "); // read the attribute list from the input stream consisting of key-value pairs // obtain the enumeration ER = PPs in the INI file. propertynames (); While (ER. hasmoreelements () {string key = (string) er. nextelement (); system. out. println (Key + "=" + PPS. getproperty (key) ;}} catch (exception e) {e. printstacktrace ();}}}

// Running result
University = hbnu
Department = cs
Class = 0801

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.