Java collection classes

Source: Internet
Author: User
Tags comparable repetition set set

Reproduced for personal study reference only, the following view please go to the original source: http://www.cnblogs.com/lxl57610/p/5822415.html

In Java, there is a set of well-designed interfaces and classes that make up the Java collection framework, making it very convenient for programmers to manipulate batches of data or object elements. All Java collections are in the Java.util package.

In the process of writing a program, use to the collection class, according to different needs, to decide which kind of collection class to use, for example, to often traverse the elements within the collection, you must use the list, if you want to ensure that the collection does not have duplicate data, you need to use set;

1) List Interface (inherited from collection interface) and its implementation class

The list interface and its implementation class are variable-capacity lists that access elements in the collection by index .

Features: The elements in the set are ordered and repeatable ;

The list is represented in the data structure as: array and vector, linked list, stack, queue.

Implementation class:
ArrayList implements an array that is variable in size and can be accessed like a linked list. It provides functionality similar to the vector class but is out of sync , it is a list implemented in array mode, allowing fast random access .

LinkedList implements a linked list that provides the best sequential access for inserting and removing elements. A linked list defined by this class can also be used as a stack or as a queue. Provides optimal sequential access to fit insertion and removal elements .

2), set set interface (inherit from collection interface) and its implementation class

Features: The elements in the collection are not sorted in a particular way , but simply adding objects to the collection is like putting something in your pocket.

Access to and manipulation of members in set is done through references to objects in set , so there can be no duplicate objects in the set.

Set also has a variety of variants, such as the ability to sort, such as TreeSet, which adds an object to a set of actions to be inserted into an ordered sequence of objects according to a comparison rule. It implements the SortedSet interface, which is the method of adding object comparisons. By iterating over the objects in the set, we can get an ascending set of objects.

Implementation class:

HashSet can quickly locate an element, it is important to note that the object that is deposited into the HashSet must implement the Hashcode () method ;

TreeSet The elements into which they are stored .

3) Map map interface and its implementation class

The map is a separate interface and does not inherit from the collection. Map is a container that associates key objects with value objects.

Features:key does not allow repetition .

Mappings are significantly different from sets or lists, and each item in the map is paired, and map is the container that associates the key object with the value object. Each object stored in the map has an associated keyword (key) object that determines where the object is stored in the map, and must be supplied with the corresponding keyword when retrieving the object, as if looking up a word in the dictionary. The keyword should be unique, meaning that the key object in the map does not allow repetition, which is to ensure consistency of the query results.

The keyword itself does not determine where the object is stored, it needs to be processed over a hashing (hashing) technique, producing an integer value called a hash code, which is usually used as a bias, relative to the starting position of the memory region assigned to the map. This determines where the keyword/object pair is stored. Ideally, hash processing should result in a uniformly distributed value within a given range, and each keyword should have a different hash code.

Implementation class:

HashMap implements a key-to-value mapping hash table, which takes a key to the value object, does not have a sequence, gets the value through get (key), allows the storage of an empty object, and allows the key to be empty (since the key must be unique, of course there is only one);

HashTable implements an image, all keys must be non-empty . In order to work efficiently, the class defining the key must implement the Hashcode () method and the equal () method . This class is an inheritance of the previous Java implementation and is usually better used in other classes that implement the image.

Select TreeMap when the order of the elements is important, and use hashmap when the elements do not have to be stored in a particular order. The use of Hashtable is not recommended because HashMap provides all the similar features and is faster. HashMap can also be converted to synchronous when you need to use it in a multithreaded environment.

properties are typically stored in the form of a key-value pair after the property file is read into the stream to facilitate reading of the data.

4), Iterator interface

The iterator interface is located in the Java.util package, which is an iterator that iterates over the collection.

A collection container (such as List, Set, map, etc.) itself provides a way to handle the placement and removal of elements, but a single selection of elements is restricted. So we're going to use iterator to select the element in the container, which converts the container into a sequence.

Iterator Iter=object.iterator ();

while (Iter.hasnext ()) {}

The following are some of the questions that I often ask in interviews:

What is the difference between 1.Collection, set and list?
There is no specified order between the collection objects, allowing duplicate elements and multiple null element objects; It is the parent class of the Set and list interface, and is the most general type of the collection interface;
There is no specified order between the set element objects, no duplicate elements are allowed, and at most one null element object is allowed;

The list of element objects has a specified order, allowing repeating elements and multiple null element objects;

2.linkedlist,arraylist,vector,stack,queue difference? NodeList difference?

1) LinkedList chain access, connected by pointers, suitable for frequent insertion and deletion in the middle of a linked list.

2) ArrayList like an array of forms, according to the ordinal storage, random access speed is very fast.

3) Vector vectors are stored according to each element ordinal, and the size of the array can grow dynamically, which is more efficient for high-capacity data storage.

4) stack stacks, advanced post-out arrays.

comparison and selection of these classes:

If you are involved in operations such as stack queues, you should consider stack,queue in the list

For quick Insert Delete elements, you should use LinkedList

If you need to quickly randomly access elements, you should choose ArrayList

If the program is in a single-threaded environment, select the non-synchronous class

If in multi-threading, the synchronization class vector, Stack and Hashtable, and their subclasses are selected.

several interview FAQs:

What is the difference between ArrayList and vectors? What's the difference between HashMap and Hashtable?

Vectors and hashtable are thread-synchronized (synchronized). In performance, ArrayList and HashMap are better than vectors and Hashtable respectively.

Explaining the architecture of the Java collection

a:list,set, andMap are the main three interfaces in this set system.

where List and Set inherit from the Collection interface.

Set does not allow elements to be duplicated. HashSet and TreeSet are the two main implementation classes.

The List is ordered and allows elements to be duplicated. ArrayList,LinkedList, and vectors are the three main implementation classes.

      mapcollection interfaces are different. mapkey value< A collection of mappings for span lang= "ZH-CN", where keykey cannot be duplicated, but valuehashmaptreemaphashtable

The SortedSet and sortedmap interfaces sort the elements by the specified rules, sortedmap the key column

Comparable and comparator differences

A: when you call the Java.util.Collections.sort list method to sort, the Object in the list must be implemented comparable interface.

  Java.util.Collections.sort (List list,comparator c), you can temporarily declare a Comparator to implement sorting.        Collections.sort (imageList, New Comparator () {public            int compare (object A, object B) {                int ordera = Integer. parseint ((Image) a). Getsequence ());                int orderb = Integer.parseint ((Image) b). Getsequence ());                return ordera-orderb;           }        });

If you need to change the sorting order

Change to return Orderb-ordera .

Brief description of Equals () and Hashcode ()

What's the difference between heap and stack?

1.heap is a heap and stack is a stack.

2.stack of space is automatically allocated and freed by the operating system, and heap space is manually applied and released, and the heap is commonly assigned with the New keyword.

3.stack space is limited, and the heap space is a large free zone.

If you just declare an object, assign it to the address space in the stack memory first .

If you instantiate it again, it will be assigned an address in heap memory.

Next look at what is NodeList, NodeList and arguments are not ordinary arrays, they have some basic properties of the array but not exactly an array. by literal means NodeList is a collection of DOM operations (getElementsByTagName, etc.) that are collections rather than ordinary arrays, but they have some properties of the array, such as length, subscript index, but They also have their own attributes, such as item, and NodeList's biggest feature is timeliness (live). About NodeList Online related resources are not many, if readers are familiar with this piece of content, welcome to comment or send me email [email protected].

The difference between 3.hashmap,hashtable,treemap,weakhashmap? Concurrenthashmap difference?

about Hashmap,hashtable,treemap, the above has been said in very detailed;

Weakhashmap is an improved hashmap that has a weak reference to key and is recycled by GC if a key is no longer externally referenced; a friend who is interested in in-depth understanding of weakhashmap can view this post Ttp://mikew ang.blog.51cto.com/3826268/880775;

Concurrenthashmap is a thread-safe HASHMAP implementation that supports high concurrency and high throughput in Java 5.          Allowing multiple modifications to be performed concurrently, the key is the use of lock separation technology. Friends who are interested in understanding Concurrenthashmap can view this sticker http://www.iteye.com/topic/344876.

Add:

Linkedelist and ArrayList both implement the list interface, but they do not work the same way. The main difference between them is that ArrayList is a resizable array, and LinkedList is a two-way link string (doubly LinkedList). ArrayList is more popular and ArrayList is more suitable than linkedlist in many scenarios. In this article we'll look at the differences between Linkedelist and ArrayList, and we'll try to see what scenarios are more appropriate for using LinkedList instead of ArrayList.

The difference between LinkedList and ArrayList

The difference between LinkedList and ArrayList comes mainly from the differences between the array and the LINKEDLIST data structures. If you are familiar with arrays and linkedlist, you can easily draw the following conclusions:

1) Because array is an index-based data structure, it is very fast to use an index to search for and read data in an array. The time complexity of getting data in an array is O (1), but deleting the data is expensive because it requires all the data in the array to be re-queued.

2) The insertion is faster than for arraylist,linkedlist. because LinkedList does not need to change the size of the array like ArrayList, it does not need to reload all the data into a new array when the array is full, which is the worst case of ArrayList, the time complexity is O (n), The time complexity of insertion or deletion in LinkedList is only O (1). ArrayList also needs to update the index when inserting data (in addition to inserting the tail of the array).

3) similar to inserting data, when deleting data, LinkedList is also better than ArrayList.

4) LinkedList requires more memory because the location of each index of ArrayList is the actual data, and each node in LinkedList stores the actual data and the location of the front and back nodes.

What scenario is more appropriate to use LinkedList instead of ArrayList

As I mentioned earlier, ArrayList is more popular in many scenarios, but in some cases linkedlist is more appropriate. Such as:

1) Your app does not randomly access the data. Because if you need the nth element in LinkedList, you need to count from the first element to the nth data and then read the data.

2) Your app more insert and delete elements, less read data. Because inserting and deleting elements does not involve rearrangement of data, it is faster than ArrayList.

These are the differences between ArrayList and LinkedList. When you need an out-of-sync index-based data access, use ArrayList as much as possible. ArrayList is quick and easy to use. But remember to give the appropriate initial size, as much as possible to reduce the size of the change array.

Java collection classes

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.