Java Collection Framework 2

Source: Internet
Author: User

8. Enumeration (enum) Use example

The simple form of declaring an enumeration type is as follows:

enum enum class name {value 1[, value 2, ...]};

Example 8. Adds a secondary method to the enumeration class.

 Packageset; Public enumSize {SMALL ("S"), MEDIUM ("M"), LARGE ("L"), Extra_large ("XL"); PrivateString num; //define private constructors, no incoming parameters    PrivateSize () { This(NULL); }    //defines a private constructor, passing in the string num as a parameter    PrivateSize (String num) { This. num =num; }    //define the public Getnum method to get the value of Num     PublicString Getnum () {returnnum; }}

Example 9. The corresponding price is output according to the model number entered by the user.

 Packageset; Public enumsize {SMALL (18.8), MEDIUM (26.8), LARGE (32.8), Extra_large (40.8); Private DoubleCost ; //define private constructors, no incoming parameters    Privatesize () { This(0); }    //defines a private constructor, passing in the string num as a parameter    PrivateSizeDoubleCost ) {         This. Cost =Cost ; }    //define the public Getnum method to get the value of Num     Public DoubleGetcost () {returnCost ; }}
 Packageset;ImportJava.util.Scanner; Public classShowclothcost { Public Static voidMain (string[] args) {Scanner in=NewScanner (system.in);        Size Si;        String type; BooleanGoon =true; System.out.println ("Please enter the clothing model, including: Small,medium,large,extra_large, empty line means the end!" ");  while(Goon) {type=in.nextline (). toUpperCase (); if(Type.length () >0) {Si= (size) enum.valueof (size).class, type); System.out.println (Type+ "The price is:" +si.getcost ()); }            ElseGoon=false;    } in.close (); }}

The result of the program operation is:

Please enter the clothing model, including: Small,medium,large,extra_large, empty line means the end! SmallsmallPrice is: 18.8mediummediumPrice is: 26.8largelarge Price is:32.8Extra_largeextra_ The price of large is:40.8

9. Enumeration set (Enumset) using the example

Enumset does not define a construction method, and to create an object of that class, it must be implemented by its factory method. The methods used to create an enumeration set are many, and are static methods, which are called factory methods.

Example 10. Create the Enumset sample.

The following program uses the size class in example 9 above.

 Packageset;ImportJava.util.EnumSet;ImportJava.util.Iterator; Public classDemoenumset { Public Static voidMain (string[] args) {Enumset<size> Enumset =enumset.of (size. SMALL, size.        MEDIUM); System.out.println ("The element that was owned when the collection was created:");        Showenumset (Enumset); System.out.println ("Complements the elements that are owned by the set:");        Showenumset (Enumset.complementof (Enumset)); Enumset.add (size.        LARGE); Enumset.add (size.        Extra_large); System.out.println ("The element that you have added after is:");        Showenumset (Enumset); System.out.println ("The added post-complement has elements that are:");    Showenumset (Enumset.complementof (Enumset)); }    Private Static voidShowenumset (enumset<size>Enumset) {Iterator<size> it =Enumset.iterator ();  while(It.hasnext ()) System.out.print (It.next ()+" ");            System.out.println (); }}

The results of the program run as follows:

The elements owned by the collection when it was created: SMALL MEDIUM The elements owned by the complement: LARGE Extra_large The element that was added after the addition is: SMALL MEDIUM LARGE Extra_large The elements that are added after the complement are:

10. Common algorithms

Example 11. Examples of simple algorithms used in collections.

 Packageset;ImportJava.util.*; Public classDemoalgorithom { Public Static voidMain (string[] args) {ArrayList<Integer> Al =NewArraylist<integer>();        Integer Elem;  for(inti=0;i<10;i++) Al.add (int) (Math.random () *1000)); System.out.println ("The generated data is:");                Showlist (AL); Elem=Collections.max (AL); System.out.println ("Max data is:" +elem); Elem=Collections.min (AL); System.out.println ("Minimum data is:" +elem);        Collections.reverse (AL); System.out.println ("The data after inversion is:");    Showlist (AL); }    Private Static voidShowlist (arraylist<integer>al) {         for(Integer elem:al) System.out.print (Elem+" ");            System.out.println (); }}

The results of the program run as follows:

The resulting data is:767 235 533 336 563 474 654 881 733 The maximum data is:342 the smallest data is: the data after the 881 inversion is:

11. Sorting

Example 12. Sorting examples.

 Packageset;Importjava.util.ArrayList;Importjava.util.Collections; Public classDemosort { Public Static voidMain (string[] args) {ArrayList<Integer> Al =NewArraylist<integer>();        Integer Elem;  for(inti=0;i<10;i++) Al.add (int) (Math.random () *1000)); System.out.println ("The generated data is:");                Showlist (AL);        Collections.sort (AL); System.out.println ("The sorted data is:");    Showlist (AL); }    Private Static voidShowlist (arraylist<integer>al) {         for(Integer elem:al) System.out.print (Elem+" ");            System.out.println (); }}

The result of the program operation is:

The data is generated as:967 847 714 896 288 836 784 994 923 749 The sorted data are:

12. Two points Search

Example 13. Two-point lookup example.

 Packageset;ImportJava.util.*; Public classDemobinsearch { Public Static voidMain (string[] args) {ArrayList<Integer> Al =NewArraylist<integer>();        Integer key; BooleanGoon =true; intindex; Scanner in=NewScanner (system.in);  for(inti=0;i<10;i++) Al.add (int) (Math.random () *1000));        Collections.sort (AL); System.out.println ("The sorted data is:");        Showlist (AL); System.out.println ("Please enter the keyword you want to find, less than 0 means end!" ");  while(Goon) {key=In.nextint (); if(key>0) {Index=Collections.binarysearch (AL, Key); if(index>=0) System.out.println (The index of the keyword "+key+" is: "+index); ElseSystem.out.println ("Keyword" +key+ "not Found!" "); }ElseGoon=false;    } in.close (); }    Private Static voidShowlist (arraylist<integer>al) {         for(Integer elem:al) System.out.print (Elem+" ");            System.out.println (); }}

The result of the program operation is:

the sorted data is:192 213 303 381 409 761 858 931 Please enter the keyword you want to find, less than 0 means end! the index of the keyword 60 is:0381 keyword 381 is indexed as:5100 keyword 100 not found! -1

13. Vector classes (vectors) using examples

Example 14. Vector use example.

 Packageset;ImportJava.util.*; Public classDemovector { Public Static voidMain (string[] args) {Vector<String> v =NewVector<string> (4); V.add ("Test0"); V.add ("Test1"); V.add ("Test0"); V.add ("Test2"); V.add ("Test2"); System.out.println ("The elements in the vector are:");        Showvector (v); V.remove ("Test0"); V.remove (0); System.out.println ("Now the number of elements in the vector is:" +v.size ()); System.out.println ("The elements in the post-deletion vector are:");    Showvector (v); }    Private Static voidShowvector (vector<string>v) {Iterator it=V.iterator ();  while(It.hasnext ()) System.out.print (It.next ()+" ");            System.out.println (); }}

The running result of the program is:

The elements in the vector are:
Test0 Test1 Test0 Test2 Test2
Now the number of elements in the vector is: 3
The elements in the post-deletion vector are:
Test0 Test2 Test2

14. Stack Use example

Example 15. Use the stack to reverse the string output.

 Packageset;ImportJava.io.*;ImportJava.util.*; Public classreversestring { Public Static voidMain (string[] args) {fileinputstream fin;        FileOutputStream Fout; Stack<Character> stack =NewStack<character>(); Charch; Try{fin=NewFileInputStream (filedescriptor.in); System.out.println ("Please enter a line of characters:");  while((Ch= (Char) Fin.read ())! = ' \ r ') Stack.push (CH);            Fin.close (); System.out.println ("Reverse output is:"); Fout=NewFileOutputStream (filedescriptor.out);  while(!stack.empty ()) Fout.write (Stack.pop ());        Fout.close (); } Catch(Exception e) {System.out.println ("The input and output stream is wrong!" "); }            }}

The result of the program operation is:

Please enter a line of characters: Helloworld! reverse output is:!dlrow Olleh

Java Collection Framework 2

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.