Javase Basic Review Strategy "seven"

Source: Internet
Author: User
Tags comparable shuffle

What is a container? The common container refers to the container which can be loaded with other things, the array which we mentioned earlier is one of the containers, and the concept of the container can be understood in Java as the vessel used to store other objects. Let's take a look at the container classes that Java provides for us.

1. Container API:

The container API provided by J2SDK is located within the Java.util package, and the class diagram structure of the container API is as follows:

   

2, the composition of the Java container:

Collection interface-Defines a method for accessing a set of objects, whose sub-interface set and list define the access mode respectively. The data objects in set are not sequential but can not be duplicated, the list of objects in order and can be repeated, the list is subdivided into LinkedList and ArrayList, from the name should be able to see its differences, linkedlist in the form of a linked list to store data, ArrayList stores the data in an array way. Finished collection interface, the following we look at the map interface, set and list are single-value storage, and map provides a key-value pair of the way to store data, the key and the value of one by one mappings between.

3, the method of collection interface definition:

int size (): The number of objects in the container

Boolean IsEmpty (): Is empty

void Clear (): Empty

Boolean contains (object element): is not a containing element object

Boolean Add (object Element): Add an Element

Boolean remove (object element): Remove Element Object

Iterator Iterator (): Returns a Iterator object that iterates through the objects in the container

Bollean Containsall (Collection C): whether to include all objects in the C container

Boolean AddAll (Collection C): Add all objects in the C container to the container

Boolean RemoveAll (Collection c): Removes all objects that exist in the C container from the container

Boolean retainall (Collection C): asks the intersection of the current collection class and the C container

Object[] ToArray (): Converts all objects in the container to the corresponding array

4. Iterator Interface:

All containers that implement the collection interface have a iterator method that returns an object that implements the Itertaor. The iterator object, called an iterator, is a convenient implementation of the traversal of elements in a container.

5, the method of iterator interface:

Boolean Hasnext (): Determines whether there are elements to the right of the cursor

Object Next (): Returns the element to the right of the cursor and moves the cursor to the next position.

void Remove (): Removes the element to the left of the cursor and moves the cursor to the next position, which can only be performed once

 Public classIter {/**     * @paramInterator Interface*/     Public Static voidMain (string[] args) {Collection coll=NewHashSet (); Coll.add (NewInteger (1)); Coll.add (NewInteger (2)); Coll.add (NewInteger (3)); Iterator it=Coll.iterator ();  while(It.hasnext ()) {//determine if the next position is emptyInteger i =(Integer) it.next (); if(!i.equals (NewInteger (1)) {System.out.println (i); }Else{it.remove ();//removed from            }        }    }}

6. Enhanced for Loop:

A new method of JAVA SDK1.5 is quite simple for traversing an array or collection. The flaw is that it is not easy to access subscript values for array elements, and it is not easy to delete elements in a container when compared to iterator. Conclusion: It is not recommended to use an enhanced for loop in addition to simply traversing and reading the contents. How to use:

 Public classTest {/**     * @paramEnhanced for Loop*/     Public Static voidMain (string[] args) {Collection<String> coll =NewArraylist<string>(); Coll.add (String.valueof (A)); Coll.add (String.valueof ("B")); Coll.add (String.valueof (C));  for(String str:coll) {System.out.println (str); }    }}

7. Set interface:

The set interface is a sub-interface of the collection interface, and the set interface does not provide an additional method, but the elements in the container class that implement the set interface are not sequential and cannot be duplicated. The set container is similar to the concept of a collection in mathematics, and the set container classes provided in the J2SDK API are HashSet and TreeSet.

 Public class Test {    /**     @param  set interface      */public      staticvoid  main (string[] args) {        new  HashSet ();        Coll.add ("Hello");        Coll.add ("word");        Coll.add (new Integer);        System.out.println (coll);    }}

8. List interface:

The list interface is a sub-interface of the collection interface, and the elements in the list container are not sequential and can be duplicated. The elements in the list container correspond to an integer ordinal that records its position in the container. The list container classes provided in the J2SDK API are ArrayList, linklist, and so on.

9. Common methods:

void sort (list): Sort the elements in a list

void Shuffle (list): Random Ordering of elements in list

void reverse (List): reverse-order the elements in list

void Fill (List, object): Overrides the list container with a specific object

void copy (list dest, list src): Copies the elements in the SRC container into the dest container

int BinarySearch (list, object): A list container of the order, using the binary lookup method to find a specific object

 Public classTest {/**     * @paramList Interface*/     Public Static voidMain (string[] args) {List L1=NewLinkedList (); List L2=NewLinkedList ();  for(inti=0; i<5; i++) {L1.add (i+1); }         for(inti=0; i<5; i++) {L1.add (A); } System.out.println (L1);//Original OrderCollections.shuffle (L1);//Random SortSystem.out.println (L1); Collections.reverse (L1);//reverse OrderSystem.out.println (L1); Collections.sort (L1);//SortSystem.out.println (L1); System.out.println (Collections.binarysearch (L1,3));//binary FindCollections.copy (L2, L1);//CopySystem.out.println (L2); }}

10. Comparable interface:

The elements in the list container can be sorted, so what sort is it based on? All classes that can be sorted implement the Java.lang.Comparable interface, with only one method for the comparable interface: public int CompareTo (Object obj); Return value: 0 for This==obj, positive for this>obj; negative for this<obj. A class that implements the comparable interface defines the ordering method for the class object by implementing the CompareTo method. Examples of sorting names:

 Public classNameImplementscomparable{/**     * @paramcomparable Interface*/    PrivateString LastName; PrivateString Fastname;  PublicString Getlastname () {returnLastName; }     Public voidsetlastname (String lastName) { This. LastName =LastName; }     PublicString Getfastname () {returnFastname; }     Public voidsetfastname (String fastname) { This. Fastname =Fastname; }     Public intcompareTo (Object arg0) {name Name=(Name) arg0; intLASTCMP =Lastname.compareto (name.lastname); return(lastcmp!=0?)LastCmp:fastName.compareTo (name.fastname)); }}

11. Map Interface:

The class that implements the map interface is used to store key-value pairs, and the values stored in the map are identified by keys, so the keys in the map cannot be duplicated.

12. Map Common methods:

Object put (object key, Object value): add Element

Object get (Object key): Takes out key value key corresponding to value

Object remove (Object key): Remove key value key corresponding to value

Boolean ContainsKey (Object key): Determine if a key value exists in the map container

Boolean Containsvalue (Object value): Determine if a value exists in the map container

int size (): Returns the length of the map container

Boolean IsEmpty (): Determines whether the map container is empty

void Clear (): Empty the Map container

For the Java container This chapter summarizes here, for automatic packaging and unpacking, generics, due to the limitations of the text description, it is no longer discussed here, if you have a good understanding, but also look at the message discussion.

  

Javase Basic Review Strategy "seven"

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.