Enter the container category of the holding object (container class) in Java, java container

Source: Internet
Author: User

Enter the container category of the holding object (container class) in Java, java container

Java containers can be said to be the basic tool to enhance the programming capability of programmers. This series will give you a deep understanding of the container class.

If the number and lifecycle of objects are fixed, we naturally do not need complicated data structures.

We can hold objects by creating references, such

Class clazz;

You can also use arrays to hold multiple objects, such

Class[] clazs = new Class[10];

However, in general, we do not know how many objects to create or how to create objects. Arrays can only create objects with a fixed length. To make the program more flexible and efficient, the Java class library provides a complete set of container classes and provides a complete solution to the above problems.

 

2.Container category

Observe, we can conclude that the container is mainly divided into two types, two interfacesCollection and MapTwo different object storage methods are defined.

CollectionUsed to save a single element,MapSave the associated key-value pairs. PassGenericTo specify the Data Type stored in the container.IteratorThe purpose of the design is to traverse container elements when the specific type of container is unknown. The remaining container types inherit the two interfaces.

In actual encodingUpward TransformationIs an interface, which is widely used in both code and code. As follows:

 

import java.util.*;public class TestCollection {    public static void main(String[] args){        Collection<Integer> c = new ArrayList<Integer>();        for(int i = 0; i < 10; i++){            c.add(i);            }        for(Integer i : c){            System.out.print(i + ", ");        }    }} 

 

Note: because the List interface has more methods than Collection, it is more appropriate to convert ArrayList to List in practical applications.

Friends who just came into contact with the container may only use Collection and Map as interfaces. In fact, this is not the case. There are actually six interfaces in the container.

3.Seven interfaces in Container

WhereThe List, Queue, and Set interfaces inherit the Collection interfaces.And the remaining interfaces are independent of each other and have no inheritance relationship. The List and Set interfaces are used to identify whether duplicate elements are to be included,Iterater iteratorIt is used with foreach for a more flexible iteration set. The Comparable interface is used for comparison.

 

4.Functions of various containers (mainly Class Analysis)

  • Collection Interface
    • List interface (compared to Collection, a new method is added)
      • ArrayList

The List interface is similar to a dynamic array and is suitable for a large number of random accesses. However, insertion and deletion are costly.

  • Shortlist

The List interface is similar to a linked List and provides optimized sequential access. Low Cost for insertion and deletion, and high cost for Random Access

  • Set interface (method and Collection are identical)
    • HashSet

HashSet usedHash FunctionThis greatly improves the access speed. Objects stored in HashSet must be defined.HashCode ()

 

import java.util.*;public class IntegerSet{  private static Random rand;   public static void main(String[] args){     rand = new Random(47);      Set<Integer> intset = new HashSet<Integer>();      for(int i = 0; i < 10000; i++){          intset.add(rand.nextInt(30));      }      System.out.println(intset);  }}

 

In this example, intset is inserted 10000 times, because the number of the final output results of repeated elements is not retained <= 30.

  • TreeSet

Use TreeSetRed/black treeTo store elements. The benefit of the red/black tree is that the set can be maintained after being inserted.Orderliness.

 

import java.util.*;public class SortIntegerSet {  private static Random rand;   public static void main(String[] args) {     rand = new Random(47);     Set<Integer> sintset = new TreeSet<Integer>();       for(int i = 0; i < 10000; i++){          sintset.add(rand.nextInt(20));       }       System.out.println(sintset);  }}

 

  • LinkedHashSet

As the name implies, javashashset usesLinked list to keep insertion orderTo improve query efficiency, howeverHash.

  • Queue Interface
    • Shortlist

The Queue List implements the Queue interface and provides methods to support Queue behavior. In future series, we will explain how to use

Queue List implements queues.

  • PriorityQueue

Unlike normal queuesHighest priority. You can provide your ownComparatorTo modify

Default priority.

  • Map Interface
    • HashMap

HashMap uses the hash mechanismQuick access.

  • TreeMap

TreeMap maintains "key"In sorting statusThe access speed is not as high as that of HashMap.

  • LinkedHashMap

LinkedHashMap persistence ElementInsertTime sequence, and provides hash for fast access

Hash Implementation of Map is very important. Understanding of Map principles (associated arrays, etc.) and hashCode () methods will be analyzed one by one in this series.

 

5.Summary

Based on the study in this article, I believe that the reader's usage, classification, and containerLevelStructure and common containerBasic functions and usageHave a clearer understanding. However, to better use the container class, you must understand the specific methods, source code, andThread Security. In the subsequent sections of this series, we will continue to discuss these content in depth.

If this article is helpful to you, I would like to recommend it to you ~

Author: I'm coding
Link: http://www.cnblogs.com/ACFLOOD/
Copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

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.