Java Collection-collection

Source: Internet
Author: User

Revisit the knowledge of Java collections, which are often involved in interviewing and project development to record.


Declaring an array is a sequence of contiguous spaces in the memory space. Arrays are a relatively common data structure, but in project development, because of certain uncertainties, it is necessary to use a set to implement, such as:

1, the size of the array is fixed, for capacity expansion, array does not support;

2, the array element type is the same data type, the collection can store different data type elements.

At the same time, the array and collection are related, using the corresponding ToArray () and Arrays.aslist () methods can recall the conversion. The collection collection can be interpreted as a dynamic array, but the contents of the collection object can be arbitrarily expanded.

<1> Collection System

list, set, and map are the important three interfaces in the set system, List,set have similarity, all inherit from collection interface, it is a set of single element, and map is a two-column element collection.


<1.1>list Interface
  The API reads:list is an ordered Collectionthat allows you to precisely control where each element is inserted. The user is able to access the elements in the list by using an index (where elements are positioned in the list , similar to array subscripts, and subscripts starting with 0 ), which is similar to an array of Java . The list in Java is an efficient extension of the data that can hold any type of element if it is created without generics, and, if used, can only accommodate elements of the specified type of the generic.

set differs, list allows the same elements, and allows the element to be null . An object can be stored repeatedly into the list collection, and each time a add () method is called, the object is inserted into the collection. In fact, the collection of collections uses an index variable to point to this object. list can take all elements in addition to iterator interface, and get ( Index i) explicitly specifies the first few elements.
implements list interfaces commonly used classes have linkedlist , Span lang= "en-US" >arraylist , vector and stack .

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:12PX;" ><span style= "Font-family:simsun;" >                List List = new ArrayList (); Random random = new random ()//Add random elements to the list;for (int temp =0;temp<5;temp++) {list.add (New Integer (RA Ndom.nextint (10)));} SYSTEM.OUT.PRINTLN (list); Iterator it = List.iterator ();//iterator the list elements;while (It.hasnext ()) { System.out.print (It.next () + "--");} </span></span>

<1.1.1>linkedlist class
The LinkedList implements a list interface that allows null elements. In addition to implementing the list interface, the LinkedList class provides a uniform naming method for the get, remove, and insert elements at the beginning and end of the list. These operations allow the link list to be used as a stack, queue , or double-ended queue .

Note LinkedList does not have a synchronization method. If multiple threads access a list at the same time, you must implement access synchronization yourself. One workaround is to construct a synchronized list when the list is created:
List List =collections.synchronizedlist (new LinkedList (...));

<1.1.2>arraylist class
ArrayList implements a variable-size array. ArrayList implements an optional list operation that allows all elements, including null. Like LinkedList, ArrayList is also unsynchronized (unsynchronized).

<1.1.3>vector class
Vector classes can implement an array of objects that can grow. Like an array, it contains components that can be accessed using an integer index. However, the size of the vector can be increased or reduced as needed to accommodate the addition or removal of items after the vector is created. The difference is that vectors are thread-synchronized.

<1.1.4>stack class
Stack inherits from Vector and implements a last-in-first-out stack. The stack provides 5 additional ways to make the vector available as a stack. The basic push and pop methods, and the Peek method to get the stack top element, the empty method tests if the stack is empty, and the search method detects the position of an element on the stack. Stack has just been created as an empty stack.

<1.2>set interface

Set is a collection that does not contain duplicate elements, that is, any two elements E1 and E2 have E1.equals (E2) =false,set have a maximum of one null element, it is obvious that the constructor of the set has a constraint condition, The passed-in collection parameter cannot contain duplicate elements. Set can be broadly divided into two categories: unordered set and sort set, unordered set including HashSet and Linkedhashset, sort set mainly refers to TreeSet. where HashSet and linkedhashset can contain null.

<1.3>map interface

map " Key-value key value pair " set similar, java map There are also two kinds: sorted and unordered, unordered including hashmap , hashtable treemap linkedhashmap

Linkedhashmap is a HashMap a subclass that preserves the order of insertions, and if the order of output needs to be the same as the input, select Linkedhashmap .

More topics in the interview

1 . The difference between HashMap and Hashtable

all belong to Map interface, which implements the mapping of a unique key to a specific value.    

(1). Historical reasons :

Hashtable is based on the old Dictionary of the class, HashMap is a Java 1.2 introduced by Map an implementation of the interface   

(2). Synchronization of :

Hashtable is thread-safe, that is, synchronous, and HashMap The thread program is unsafe, not synchronous.   

(3). values:

HashMap classes are not categorized or sorted. It allows a null key and multiple null values.  

Hashtable similar to HashMap , but not allowed NULL Keys and NULL values.

(4). Efficiency:

Hashtable than HashMap slow, because it is synchronous.

How to make HashMap Sync

HashMap can be done by Map m =collections.synchronizedmap ( HashMap ) to achieve the effect of synchronization.

2 . The difference between ArrayList and vectors

ArrayList with the Vector mainly from two aspects,  .

(1). Synchronization of :

Vector is thread-safe, that is, synchronous, and ArrayList It is unsafe for the thread program, not synchronous.

(2). Operation :

since the Vector supports multi-threaded operation, the performance is not as ArrayList .

(3). Data Growth :

ArrayList and the Vector have an initial capacity size, and when the number of elements stored in them exceeds the capacity, you need to increase ArrayList and the Vector storage space, each time the storage space is increased, not only one storage unit is added, but multiple storage units are added.

Vector By default the original is increased by one times, ArrayList The default adds the original 0.5 times.

Vector we can set the size of the growth by ourselves, ArrayList No related methods are provided.

3 , LinkedList with the ArrayList What's the difference?

both of these implementations are List interface, the difference is:

( 1 ArrayList LinkedList

( 2 get access list when any element inside, arraylist linkedlist good performance. linkedlist get

( 3 ), for new and deleted operations LinkedList Stronger than ArrayList , because ArrayList to move data

Additional:

LinkedListrealized theListinterface, allowingNULLelement. AlsoLinkedListprovide additionalGet,Remove,Insertmethod inLinkedListthe first or the tail. These operations enableLinkedListcan be used as a stack (Stack), Queue (Queue) or two-way queue (deque).

Note linkedlist does not have a synchronization method. If multiple threads access a List at the same time , you must implement access synchronization yourself. One workaround is to construct a synchronized listWhen the list is created:

List List =collections.synchronizedlist (new LinkedList ( ... ));

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Collection-collection

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.