Java Container class Basics

Source: Internet
Author: User
Tags addall

Java Container class Basics

Java Utility Class Library provides a fairly complete set of container classes, the basic type is list,set,map,queue. They all have features, such as set that only holds one object for each value, and map allows you to associate objects with objects. In addition, the Java container class can automatically adjust the dimensions. So, unlike arrays, you can place any number of objects into a container without worrying about how large the container should be.

The Java container class has 4 interfaces, each of which is mentioned above List,set,map,queue; Ideally, the code you write is mostly about dealing with these interfaces, and the only place you need to specify the exact type you want to use is when you create it. For example, you can create a list:

List<apple> list=new arraylist<apple> ();

The purpose of using the interface here is that when you need to modify your implementation, you only need to modify it where you created it, so you can modify it as follows:

List<apple> list=new linkedlist<apple> ();

Therefore, you should create an object of a specific class and then convert it to the corresponding interface, and then use that interface in the rest of the code. However, this approach does not always work because some classes have additional functionality. For example, LinkedList has additional methods that are not included in the list interface, so if you need to use these methods, you cannot convert them to a more generic interface.

Here, we will focus on the basic knowledge and typical usage of the Java container class.

1, Basic concept

The purpose of the Java Container Class library is to save the object and divide it into two different concepts:

1) Collection: A sequence of independent elements. The list must save the elements in the order in which they are inserted, the set cannot have duplicate elements, and the queue determines the order of the elements according to the queuing rules.

2) Map: A pair of "key-value pairs" objects that allow you to use keys to look up values. ArrayList allows you to use numbers to look up values, and in a sense it associates numbers with objects. Map allows us to use an object to find another object, also known as an associative array, which should be associated with some objects and other objects.

<span style= "FONT-SIZE:18PX;" >import java.util.*;p ublic class printingcontainers{static Collection Fill (collection<string> Collection) { Collection.add ("Rat"), Collection.add ("Cat"), Collection.add ("Dog"), Collection.add ("dog"); return collection;} Static map Fill (map<string,string> map) {Map.put ("rat", "123"), Map.put ("Cat", "456"), Map.put ("Dog", "789"); Map.put ("Dog", "268"); return map;} public static void Main (string[] args) {System.out.println (Fill (New arraylist<string> ())); SYSTEM.OUT.PRINTLN (Fill (New linkedlist<string> ())); SYSTEM.OUT.PRINTLN (Fill (New hashset<string> ())); SYSTEM.OUT.PRINTLN (Fill (New treeset<string> ())); SYSTEM.OUT.PRINTLN (Fill (New linkedhashset<string> ())); SYSTEM.OUT.PRINTLN (Fill (New hashmap<string,string> ())); SYSTEM.OUT.PRINTLN (Fill (New treemap<string,string> ())); SYSTEM.OUT.PRINTLN (Fill (New linkedhashmap<string,string> ()));}} /*output:[rat, Cat, Dog, Dog][rat, cat, Dog, Dog][cat, dog, Rat][cat, dog, Rat][rat, cat, dog]{cat=456, dog=268, rat=123}{cat=456, dog=268, rat=123}{rat=123, cat=456, dog=268}*/</span> 

The two main types in the Java Container Class library are shown here, the difference being that each "slot" in the container holds the number of elements. Viewing the output, you can see that the default print behavior (using the ToString method provided by the container) produces good readability results. Collection The printed content is enclosed in square brackets, with each element separated by commas. The map is enclosed in curly braces, and the key is associated with the value by an equal sign. These containers are used here only for display purposes and are described in more detail later.

2, Common container class introduction

1) Collection

The following table lists all the methods that can be executed through collection, which are also actions that set and list can perform.

2) List

The list interface adds a number of methods to the collection base, allowing you to insert and remove elements in the middle of the list.

There are two types of lists:

• Basic ArrayList, which is adept at randomly accessing elements, but inserting and deleting elements in the middle of the list is slower (the underlying implementation: arrays).

· LinkedList, which inserts and deletes in the middle of the list at a lower cost, provides an optimized sequential access, but is relatively slow in terms of random access (the underlying implementation: a doubly linked list).

Here are some commonly used methods in the list:

Contains (): Used to determine whether an object is in the list

Remove (): To remove objects from the list

IndexOf (): Used to determine the index number of an object in the list

Sublist (): Used to create a list fragment

Retainall (): Used for "intersection" operation

Set (): Used to set the object at the specified index

3) LinkedList

LinkedList implements the basic list interface as well as the method of making it available as a stack, a queue, and a double-ended queue.

Some of these methods are only slightly different from each other, or there are only a few differences, so that these names are more applicable in a particular context. For example:

GetFirst () and element () are exactly the same, they all return the first element of the list without removing it; remove () and Removefirst () are the same, they remove and return the header of the list; Add () and AddLast () are the same, They all insert elements into the end of the list;

4) Set

Set does not save duplicate elements. The most common use of set is to test attribution, and you can easily ask if an object is in a set. The set has exactly the same interface as the collection, so there is no additional functionality, unlike the previous two different lists. In fact set is collection, but behaves differently (this is a typical application of inheritance and polymorphism);


<span style= "FONT-SIZE:18PX;" >import java.util.*;p ublic class setofoperations{public static void Main (string[] args) {set<string> set1=new Hashset<string> (); Collections.addall (Set1, "A B C D E F G H I J K L". Split (")"); Set1.add ("M"); System.out.println ("H:" +set1.contains ("H")); System.out.println ("N:" +set1.contains ("n")); Set<string> set2=new hashset<string> (); Collections.addall (Set2, "H I J K L". Split ("")); System.out.println ("Set2 in Set1:" +set1.containsall (Set2)); Set1.remove ("H"); System.out.println (SET1); System.out.println ("Set2 in Set1:" +set1.containsall (Set2)); Set1.removeall (Set2); System.out.println ("Set2 Remove from Set1:" +set1); Collections.addall (Set1, "X Y Z". Split ("")); System.out.println ("' X Y Z ' Add to Set1:" +set1);}} /*output:h: Truen:falseset2 in Set1:true[d, E, F, G, A, B, C, L, M, I, J, K]set2 in Set1:falseset2 Remove from Set1: [D , E, F, G, A, B, C, M] ' X Y Z ' Add to Set1: [D, E, F, G, A, B, C, M, Y, X, z]*/</span>

5) Map


The ability to map objects to other objects is a killer to solve programming problems;

For example, the following example:

<span style= "FONT-SIZE:18PX;" >import java.util.*;p ublic class statistics{public static void Main (string[] args) {random rand=new random (47); Map<integer,integer> m=new hashmap<integer,integer> (); for (int i=0;i<10000;i++) {int r=rand.nextInt ( Integer Feq=m.get (R); M.put (r,feq==null?1:feq+1);} System.out.println (M);}} /*output:{0=481, 1=502, 2=489, 3=508, 4=481, 5=503, 6=519, 7=471, 8=468, 9=549, 10=513, 11=531, 12=521, 13=506, 14=477, 15 =497, 17=509, 16=533, 19=464, 18=478}*/</span>

6) Queue

A queue is a typical first-in-one-out container in which things are placed from one end of the container, removed from the other, and the order in which things are placed in the container is the same as the order in which they are taken. Queues are often used as a reliable way to transfer objects from one area of a program to another, which is especially important in concurrent programming.

LinkedList provides methods to support queue behavior, and the queue interface is implemented, so linkedlist can be implemented as a queue.


<span style= "FONT-SIZE:18PX;" >import java.util.*;p ublic class queuedemo{public static void PrintQueue (queue queue) {while (Queue.peek ()!=null) { System.out.print (Queue.remove () + "");} System.out.println ();} public static void Main (string[] args) {queue<integer> queue=new linkedlist<integer> (); Random rand=new random (+), for (int i=0;i<10;i++) Queue.offer (Rand.nextint (i+10));p rintqueue (queue); Queue<character> qc=new linkedlist<character> (); for (char c: "Helloworldjava". ToCharArray ()) Qc.offer (c) ;p Rintqueue (QC);}} </span>

Some common methods of queue are listed below:

Offer (): Insert an element into the tail of the team

Peek ()/element (): Returns to the opponent without deleting

Poll ()/remove (): Remove and return to enemy


3, iterator

An iterator is an object whose work is to traverse the objects in the selection container, using only the container, not knowing or not caring about the type of the container, and achieving the purpose of reusing the code. In addition, iterators are also called lightweight objects: the cost of creating it is small;

Use of iterators:

1) Use iterator () to request that the container return a iterator ();

2) use Next () to get the next element in the container;

3) use Hasnext () to check if there are any elements in the container;

4) Remove the newly returned elements of the iterator using remove ();


Summarize

Java container diagram, commonly used in the container with a thick black line box, the Point line box represents an interface, a solid wireframe represents a specific class; a dot line with a hollow arrow indicates that a particular class implements an interface, and a solid arrow indicates that a class can generate objects that the arrows point to the class;



Here are some tips for choosing a container:

1) If you want to do a lot of random access, use ArrayList, if you often need to insert and delete elements from the middle of the table, you should use LinkedList;

2) The HashMap is designed for quick access, while the TreeMap hold key is always in the sorted state, so there is no hashmap fast. Linkedhashmap preserves the insertion order of elements, but also provides quick access through hashing.

3) TreeSet does not accept duplicate elements. HashSet provides the fastest query speed, while TreeSet keeps elements in the sorted state, Linkedhashset saves the elements in the order in which they are inserted.

4) Outdated vector,stack,hashtable should not be used in the program;



Java Container class Basics

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.