Table of Contents
Commonly used data structures in JAVA (java.util.)" >Commonly used data structures in JAVA (java.util.)
Vector
5、LinkedList
List summary: " > List summary:
API-----A collection that contains no duplicate elements. More formally, sets contain no pair of elements
7、HashSet" >7、HashSet
-------------Map-----------------
1. HashMap" >1. HashMap
2、TreeMap" >2、TreeMap
Home Java javaTutorial Summarize and share several commonly used data structures in Java

Summarize and share several commonly used data structures in Java

Aug 01, 2017 am 10:54 AM
java several kinds Commonly used

Commonly used data structures in JAVA (java.util.)

There are several commonly used data structures in java, mainly divided into Collection and map There are two main interfaces (interfaces only provide methods, not implementations), and the data structures ultimately used in the program are data structure classes inherited from these interfaces. The main relationships (inheritance relationships) are: (----See java api documentation for details!)

##Collection---->Collections                                                                               Map-----> SortedMap------>TreeMap

Collection---->List----->(Vector \ ArryList \ LinkedList)                                                  Map----- ->HashMap

Collection---->Set------>(HashSet \ LinkedHashSet \ SortedSet)

--------------Collection----------------

1. Collections

API----This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few others odds and ends.

The methods of this class all throw a

NullPointerException if the collections or class objects provided to them are null.

2、List

API----This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends.

The methods of this class all throw a

NullPointerException if the collections or class objects provided to them are null.

List is ordered Collection, use this interface to precisely control the insertion position of each element. Users can use the index (the position of the element in the List, similar to the array subscript) to access the elements in the List, which is similar to Java arrays.

##3、Vector

API---- The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of aVector can grow or shrink as needed to accommodate adding and removing items after theVector has been created. Some functions are convenient for us to use, so it is difficult to avoid the limitations of arrays, and at the same time, the performance cannot surpass arrays. Therefore, where possible, we should use arrays more. Another very important point is that Vector is thread synchronized (sychronized), which is why Vector and ArrayList an important difference.

4、ArrayList
API----Resizable-array implementation of the
List

interface. Implements all optional list operations, and permits all elements, including

null. In addition to implementing theList

interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to

Vector

, except that it is unsynchronized.)

Like Vector, it is a linked list based on an array, but the difference is that ArrayList is not synchronized. Therefore, it is better than Vector in terms of performance, but when running in a multi-threaded environment, you need to manage the synchronization of threads yourself.

5、LinkedList

API----Linked list implementation of the List interface. Implements all optional list operations, and permits all elements (includingnull). In addition to implementing theList interface, the LinkedList class provides uniformly named methods toget, remove andinsert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack,queue, ordouble-ended queue.

LinkedList is different from the previous two Lists. It is not based on arrays, so it is not limited by array performance.
Each node (Node) contains two aspects of content:
1. The data of the node itself;
2. Next node information (nextNode).
So when adding and deleting actions to LinkedList, you don’t have to move a lot of data like array-based ArrayList. This can be achieved by simply changing the relevant information of nextNode. This is the advantage of LinkedList.

List summary:

  • All Lists can only hold tables composed of a single object of different types, not Key-Value pairs. For example: [ tom,1,c ]

  • ##All Lists can have the same elements, for example, Vector can have [ tom ,koo,too,koo ]

  • ##All Lists can have null elements, such as [ tom,null,1 ]

Array-based List (Vector, ArrayList) is suitable for query, while LinkedList is suitable for add and delete operations 6. Set(Interface)

API-----A collection that contains no duplicate elements. More formally, sets contain no pair of elements

e1

ande2 such thate1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematicalset abstraction.

Set is a Collection that does not contain duplicate elements

7、HashSet

## API-----This class implements theSet interface, backed by a hash table (actually aHashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits thenull element.

##Although Set and List both implement the Collection interface, their implementation methods are quite different. List is basically based on Array. But Set is implemented on the basis of HashMap. This is the fundamental difference between Set and List. The storage method of HashSet is to use the Key in HashMap as the corresponding storage item of Set. have a look The implementation of the add(Object obj) method of HashSet can be seen at a glance.

8、LinkedHashSet

## API----Linked list implementation of the

List

interface. Implements all optional list operations, and permits all elements (includingnull). In addition to implementing theList interface, theLinkedList class provides uniformly named methods toget, remove andinsert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack,queue, ordouble-ended queue.

A subclass of HashSet, a linked list.


##9、SortedSet

API---A

Set

that further provides atotal ordering on its elements. The elements are ordered using their natural ordering, or by aComparator typically provided at sorted set creation time. The set's iterator will traverse the set in ascending element order. Several additional operations are provided to take advantage of the ordering. (This interface is the set analogue ofSortedMap.) Ordered Set,

is implemented through SortedMap. Set summary:

##(1)

The basis of Set implementation is Map (HashMap) (2) The elements in Set cannot be repeated. If you use add(Object obj) method to add an existing object will overwrite the previous object

-------------Map-----------------

Map is a key object A container associated with a value object, and a value object can be a Map, and so on, thus forming a multi-level map. For key objects, like Set, the key objects in a Map container are not allowed to be repeated. This is to maintain the consistency of the search results; if there are two key objects that are the same, then you want to get the value object corresponding to that key object. There will be a problem. Maybe what you get is not the value object you thought, and the result will be confusion. Therefore, the uniqueness of the key is very important and is in line with the nature of the set. Of course, during use, the value object corresponding to a certain key may change. In this case, the last modified value object will correspond to the key. There is no uniqueness requirement for value objects. You can map any number of keys to a value object without any problems (but it may cause inconvenience to your use. You don’t know what you are getting. is the value object corresponding to that key).

1. HashMap

API----Hash table based implementation of theMap interface. This implementation provides all of the optional map operations, and permitsnull values ​​and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

2、TreeMap

API----A Red-Black tree basedNavigableMap implementation. The map is sorted according to to the natural ordering of its keys, or by aComparator provided at map creation time, depending on which constructor is used. It is stored in order, so it has some extended methods, such as firstKey(), lastKey(), etc. You can also specify a range from TreeMap to obtain its sub-Map.

The association between keys and values ​​is very simple. Use the put(Object key, Object value) method to associate a key with a value object. Use get(Object key) to get the value object corresponding to this key object.


#------------illustrate-----------

1. The differences between several commonly used classes
1. ArrayList: Single element, high efficiency, mostly used for query
2. Vector: Single element, thread-safe, mostly used for query
3. LinkedList: Single element, mostly used for insertion and deletion
4. HashMap: The elements are in pairs, and the elements can be empty
5. HashTable: Elements are in pairs, thread-safe, elements cannot be empty
##2. Vector, ArrayList and LinkedList
##In most cases, ArrayList is the best in terms of performance, but when it comes to collections LinkedList will perform better when the elements in it need to be frequently inserted and deleted, but the performance of the three of them is not as good as that of arrays. In addition, Vector is thread synchronized. So:
If you can use an array (element type is fixed, array length is fixed), please try to use an array instead of List;
If there are no frequent deletion and insertion operations, and there is no need to consider multi-threading issues, ArrayList is preferred;

If used under multi-threaded conditions, you can consider Vector;
# #If you need to delete and insert frequently, LinkedList comes into play;
If you don’t know anything, there is nothing wrong with using ArrayList.
#3. Collections and Arrays
exist There are two classes in the Java collection class framework called Collections (note, not Collection!) and Arrays. These are powerful tools in JCF, but beginners often ignore them. According to the JCF document, these two classes provide wrapper implementations (Wrapper Implementations), data structure algorithms, and array-related applications.
I am sure you will not forget the classic algorithms such as "half search" and "sorting" mentioned above. The Collections class provides a wealth of static Methods help us easily complete these annoying tasks in data structure classes:
binarySearch: binary search.
sort: Sort, here is a method similar to quick sort, the efficiency is still is O(n * log n), but is a stable sorting method.

#reverse: Operate a linear table in reverse order. This is a classic test question on data structures in the past!
rotate: "Rotate" the linear table around a certain element as the axis.
swap: Swap the positions of two elements in a linear list.
......
Collections also has an important function It is the "Wrapper", which provides some methods to convert a collection into a special collection, as follows:
unmodifiableXXX: Convert to a read-only collection, where XXX represents six basic collection interfaces: Collection, List, Map, Set, SortedMap and SortedSet. If you insert or delete a read-only collection, an UnsupportedOperationException will be thrown.
##synchronizedXXX: Convert to a synchronized collection.
##singleton: Create a collection with only one element. Here singleton generates a single Element Set,

singletonList and singletonMap generate single-element List and Map respectively.
## Empty set: represented by the static properties EMPTY_SET, EMPTY_LIST and EMPTY_MAP of Collections.

The above is the detailed content of Summarize and share several commonly used data structures in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1654
14
PHP Tutorial
1252
29
C# Tutorial
1225
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles