Java Vamei Quick Tutorial 18 container

Source: Internet
Author: User

Vamei Source: Http://www.cnblogs.com/vamei Welcome reprint, Please also keep this statement. Thank you!

Some objects in Java are called Containers (container). A container can contain multiple objects, each of which is called an element in a container. A container is a data structure (data structure) that is encapsulated with an object.

A container full of dreams

Different data structures have different ways of organizing elements, and can have different operations. Depending on the implementation, the operational efficiency of the data structure is different. The same is true for containers in Java. We need to choose the right container to cope with the changing needs.

(For more information on data structures, refer to the paper: Algorithms and Data structures)

Array

Arrays (array) are the most common data structures. An array is an ordered collection of elements of the same type and has a fixed size (which can hold a fixed number of elements). An array can randomly access (random access) elements according to the subscript (index). In memory, an array is usually a contiguous unit of storage.

Java supports arrays of this data structure. We need to explain the type and size of each array. As follows:

public class test{public    static void Main (string[] args)    {        human[] persons = new HUMAN[2];              Array size 2        persons[0] = new Human;        PERSONS[1] = new Human;        Int[] A = {1, 2, 3, 7, 9};                   Array size 5        System.out.println (a[2]);        String[] names = {"Tom", "Jerry", "Luffy"};  Array size 3        System.out.println (Names[0]);}    }

In the description type, add a [] after the type description (Human) to indicate that it is an array. When you create a container using new, you need to describe the size of the array.

We can invoke an element by using the array name [subscript]. We can initialize the elements of the array one by one, or we can initialize the array with {} at the same time as the declaration.

For non-primitive types of arrays, such as human[], the array stores a reference to the object.

We can call the System.arraycopy () method to copy the array efficiently:

public class test{public    static void Main (string[] args)    {        int[] Afrom = {1, 2, 3, 7, 9};//array size 5
   
    int[] ATo  = new Int[3];        System.arraycopy (Afrom, 1, aTo, 0, 3);        System.out.println (ato[1]);}    }
   

System.arraycopy (), Afrom is the array that you want to copy, the ATO is the array that you want to copy, 1 is the starting position of the element that you want to copy to, and 0 is the starting position of the element where you want to store the copy in the ATO, and 3 is the total number of elements you want to copy.

Collection

The table (list) and set (set) are the two interfaces (interface) defined in Java.util. Both interfaces inherit from the collection interface. By implementing the interface, we can obtain the appropriate container.

We used to use class to describe the type of reference. In fact, we can also use Interfaces (interface) to illustrate the types of references. The object that the type reference points to must implement the interface.

Let's start with the table (list) container. List is an ordered collection of elements, so you can use subscripts to illustrate the position of the element. The elements in the collection can be equal:

Import java.util.*;p ublic class test{public    static void Main (string[] args)    {        list<string> l1 = new Ar Raylist<string> ();        L1.add ("good");        L1.add ("bad");
L1.add ("shit");
L1.remove (0);
System.out.println (L1.get (1)); System.out.println (L1.size ());} }

When we define interfaces and create containers, we use <class> to describe the types of elements that can be accommodated in a container. We will only put objects in the class class and its derived classes in the container.

The container's reference is a list type, but the container is implemented as a ArrayList class. Here is the separation of the interface from the implementation. In fact, the same abstract data structure (ADT) can have a number of implementations (such as stacks and lists) that can be implemented by the stack. This separation allows us to choose more freely how ADT is implemented.

We can define a container of the <Object> type. Since all classes in Java inherit from the object class, such a container can actually be placed into any type of object.

In the above program, the container is of type string. We use

    • Add () method to add a new element
    • The Get () method can get the elements in the container, passing an integer subscript as a parameter
    • The Remove () method removes the element from the container and passes an integer subscript as a parameter. (There is another remove (), passing the element itself as an argument)
    • The size () method is used to return the total number of elements in the container.

Official documents for List

A collection (set) is also a collection of elements. No equivalent elements are allowed in the collection, and the elements of the collection are not in order:

Import java.util.*;p ublic class test{public    static void Main (string[] args)    {        set<integer> s1 = new Ha Shset<integer> ();        S1.add (4);        S1.add (5);        S1.add (4);
S1.remove (5); System.out.println (S1); System.out.println (S1.size ());} }

The element that is added repeatedly 4 is placed only once in the container. Because set is unordered, in remove (), we pass the target element itself as an argument directly.

Official documentation for set

Both the list and the set inherit from the collection interface. Collection represents a collection of objects. Many of the methods in the list and set interfaces above actually inherit from collection, such as:

Add ("good") add element

Size () returns the total number of elements

Whether contains ("bad") contains elements

Remove ("good") Delete element

Official Documents of Collection

Collection also has a method of iterator (). This method encapsulates the collection container as a circulator (Iterator). A circulator is a collection of elements that has a next () method that returns one element at a time until the element in the loop is exhausted.

Import java.util.*;p ublic class test{public    static void Main (string[] args)    {        list<integer> l1 = new A Rraylist<integer> ();        L1.add (4);        L1.add (5);        L1.add (2);        Iterator i = L1.iterator ();        while (I.hasnext ()) {            System.out.println (I.next ());}}}    

Official documents of iterator

Map

Map is a collection of key-value pairs. Each element in the map is a key-value pair, which is a key (key) and its corresponding object value (value). For the map container, we can find the corresponding object by the key.

Hash table is a common way to implement map, refer to the paper: Hash table (hash table)

We need to declare the type of the key and value of the map. We implement a hashmap below:

Import java.util.*;p ublic class test{public    static void Main (string[] args)    {        map<string, integer> M1 = new hashmap<string, integer> ();        M1.put ("Vamei",);        M1.put ("Jerry", 5);        M1.put ("Tom",);        System.out.println (M1.get ("Vamei"));}    }

In map, we use the put () method to add elements and get the elements using the Get () method.

The map also provides the following method to return a collection:

KeySet () converts all keys to set

VALUES () converts all values to a list

Summarize

In Java, the interface of a container is separated from implementation. This gives Java programmers greater freedom of choice and, of course, adds difficulty to programming.

The interface provides us with a legitimate operation. At the effect level, different implementations have the same effect. Of course, in different contexts, the implementation details will determine the efficiency of the operation.

Finally, we refer to the relationship between the various classes and interfaces:

Java Vamei Quick Tutorial 18 container

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.