Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An overview of List, Set, and Map in the Java collection

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains the "Overview of List, Set and Map in the Java collection". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the overview of List, Set and Map in the Java collection".

Overview:

List, Set and Map are all interfaces. The first two are inherited from collection, and Map is an independent interface.

There is HashSet,LinkedHashSet,TreeSet under Set.

There is ArrayList,Vector,LinkedList under List.

There is Hashtable,LinkedHashMap,HashMap,TreeMap under Map.

There is also a Queue interface under the collection interface, which has the PriorityQueue class

Note:

Queue API is at the same level as List and Set, and both inherit collection interface.

If you look at the picture, you will find that LinkedList can implement both Queue interface and List interface. However, LinkedList implements the Queue interface. The Queue interface narrows access to LinkedList's methods (that is, if the parameter type in the method is Queue, you can only access the methods defined by the Queue interface, rather than directly accessing LinkedList's non-Queue methods), so that only the appropriate methods can be used.

SortedSet is an interface, and the elements in it (only one implementation of TreeSet is available) must be ordered.

Summary:

Connection interface (note the initials are lowercase):

-List is orderly and repeatable

ArrayList

Advantages: the underlying data structure is an array, fast query, slow growth and deletion.

Disadvantages: unsafe threads and high efficiency

Vector

Advantages: the underlying data structure is an array, fast query, slow growth and deletion.

Disadvantages: thread safety, low efficiency

LinkedList

Advantages: the underlying data structure is linked list, slow query, fast addition and deletion.

Disadvantages: unsafe threads and high efficiency

-Set is unordered, unique

HashSet

The underlying data structure is a hash table. (disordered, unique)

How to ensure the uniqueness of elements?

1. Rely on two methods: hashCode () and equals ()

LinkedHashSet

The underlying data structures are linked lists and hash tables. (FIFO insertion is orderly and unique)

1. Keep the elements in order by the linked list

two。 The hash table ensures that the element is unique

TreeSet

The underlying data structure is the red-black tree. (unique, orderly)

1. How do you ensure that elements are sorted?

Natural ordering

Comparator sort

two。 How to ensure the uniqueness of the element?

It is determined according to whether the return value of the comparison is 0.

Who exactly do we use for collection collections? (master)

The only one?

Yes: Set

Sort it?

Yes: TreeSet or LinkedHashSet

No: HashSet

If you know it's Set, but you don't know which Set it is, use HashSet.

No: List

Is it safe?

Yes: Vector

No: ArrayList or LinkedList

Many queries: ArrayList

Add and delete more: LinkedList

If you know it's List, but you don't know which List it is, use ArrayList.

If you know it's a collection collection, but you don't know who to use, use ArrayList.

If you know how to use collections, use ArrayList.

When you're done with collection, let's briefly talk about Map.

Map interface:

The image above:

The Map interface has three important implementation classes, which are HashMap, TreeMap, and HashTable.

TreeMap is ordered, HashMap and HashTable are unordered.

The method of Hashtable is synchronous, while the method of HashMap is not. This is the main difference between the two.

This means:

Hashtable is thread-safe, HashMap is not thread-safe.

The efficiency of HashMap is higher than that of Hashtable.

If there is no requirement for synchronization or compatibility with legacy code, HashMap is recommended. If you look at the source code of Hashtable, you can see that except for the constructor, all public method declarations of Hashtable have the synchronized keyword, while the source code of HashMap does not.

Hashtable does not allow null values, HashMap allows null values (both key and value allow)

The parent class is different: the parent class of Hashtable is Dictionary,HashMap, and the parent class is AbstractMap

Focus on analysis of key issues:

The difference between TreeSet and LinkedHashSet and HashSet

1. Introduction

Both TreeSet and LinkedHashSet and HashSet are data structures that implement Set in java.

The main function of TreeSet is for sorting

The main function of LinkedHashSet is to ensure that FIFO is an orderly collection (first-in, first-out)

HashSet is just a general collection of stored data

two。 Identical point

Duplicates elements: because all three implement Set interface, none of them include duplicate elements

Thread safety: none of them are thread safe. If you want to use thread safety, you can collections.synchronizedSet ().

3. Differences

Performance and Speed: HashSet inserts data the fastest, followed by LinkHashSet, and the slowest is TreeSet because of internal sorting.

Ordering: HashSet does not guarantee ordering. LinkHashSet guarantees that FIFO is sorted according to insertion order, sorting is implemented inside the TreeSet installation, and sorting rules can be customized.

Null:HashSet and LinkHashSet allow the existence of null data, but NullPointerException is reported when null data is inserted into TreeSet

4. Code comparison

Public static void main (String args []) {

HashSet hashSet = new HashSet ()

LinkedHashSet linkedHashSet = new LinkedHashSet ()

TreeSet treeSet = new TreeSet ()

For (String data: Arrays.asList ("B", "E", "D", "C", "A")) {

HashSet.add (data)

LinkedHashSet.add (data)

TreeSet.add (data)

}

/ / order is not guaranteed

System.out.println ("Ordering in HashSet:" >

/ / FIFO guarantees installation insertion order sort

System.out.println ("Order of element in LinkedHashSet:" + linkedHashSet)

/ / sort is implemented internally

System.out.println ("Order of objects in TreeSet:" + treeSet)

}

Running result:

Ordering in HashSet: [a, B, C, D, E] (out of order)

Order of element in LinkedHashSet: [B, E, D, C, A] (FIFO insertion order)

Order of objects in TreeSet: [a, B, C, D, E] (sort)

(2) comparison of two sorting methods of TreeSet

1. The introduction of sorting (taking the sorting of basic data types as an example)

Because TreeSet can sort elements according to certain rules, for example, the following example

Public class MyClass {

Public static void main (String [] args) {

/ / create a collection object

/ / sort in natural order

TreeSet ts = new TreeSet ()

/ / create elements and add

/ / 20,18,23,22,17,24,19,18,24

Ts.add (20)

Ts.add (18)

Ts.add (23)

Ts.add (22)

Ts.add (17)

Ts.add (24)

Ts.add (19)

Ts.add (18)

Ts.add (24)

/ / traversing

For (Integer I: ts) {

System.out.println (I)

}

}

}

Running result:

seventeen

eighteen

nineteen

twenty

twenty-two

twenty-three

twenty-four

two。 What if it is a reference data type, such as a custom object, how to sort it?

Test class:

Public class MyClass {

Public static void main (String [] args) {

TreeSet ts=new TreeSet ()

/ / create element object

Student s1=new Student ("zhangsan", 20)

Student s2=new Student ("lis", 22)

Student s3=new Student ("wangwu", 24)

Student s4=new Student ("chenliu", 26)

Student s5=new Student ("zhangsan", 22)

Student s6=new Student ("qianqi", 24)

/ / add the element object to the collection object

Ts.add (S1)

Ts.add (S2)

Ts.add (S3)

Ts.add (S4)

Ts.add (S5)

Ts.add (S6)

/ / traversing

For (Student s:ts) {

System.out.println (s.getName () + "-" + s.getAge ())

}

}

}

Student.java:

Public class Student {

Private String name

Private int age

Public Student () {

Super ()

/ / TODO Auto-generated constructor stub

}

Public Student (String name, int age) {

Super ()

This.name = name

This.age = age

}

Public String getName () {

Return name

}

Public void setName (String name) {

This.name = name

}

Public int getAge () {

Return age

}

Public void setAge (int age) {

This.age = age

}

}

An error was reported as a result:

Cause analysis:

An error will be reported because you don't know which sort method to sort according to.

Solution:

1. Natural ordering

two。 Comparator sort

(1)。 Natural ordering

Natural sorting requires the following operations:

Implement Comparable interface in 1.Student class

two。 Override the Compareto method in the Comparable interface

CompareTo (To) compares the order of this object with the specified object.

Public class Student implements Comparable {

Private String name

Private int age

Public Student () {

Super ()

/ / TODO Auto-generated constructor stub

}

Public Student (String name, int age) {

Super ()

This.name = name

This.age = age

}

Public String getName () {

Return name

}

Public void setName (String name) {

This.name = name

}

Public int getAge () {

Return age

}

Public void setAge (int age) {

This.age = age

}

@ Override

Public int compareTo (Student s) {

/ / return-1; / /-1 means put on the left side of the red-black tree, that is, output in reverse order

/ / return 1; / / 1 means put on the right side of the red-black tree, that is, sequential output

/ / return o; / / indicates that the element is the same, and only the first element is stored

/ / the length of the main condition name. If the length of the name is small, put it on the left subtree, otherwise on the right subtree.

Int num=this.name.length ()-s.name.length ()

/ / the length of the name is the same, but it does not mean that the content is the same. If the String object is placed before the parameter string in lexicographical order, the result of the comparison is a negative integer.

/ / if the String object is placed after the parameter string in lexicographical order, the result of the comparison is a positive integer.

/ / if the two strings are equal, the result is 0

Int num1=num==0?this.name.compareTo (s.name): num

/ / the length and content of the name are the same, which does not mean the age is the same, so it is necessary to judge the age.

Int num2=num1==0?this.age-s.age:num1

Return num2

}

}

Running result:

Lis-22

Qianqi-24

Wangwu-24

Chenliu-26

Zhangsan-20

Zhangsan-22

(2)。 Comparator sort

Comparator sorting steps:

1. Create a separate comparison class. Here, take MyComparator as an example, and let it inherit the Comparator interface

two。 Override the Compare method in the Comparator interface

Compare (T _ 1 ~ T _ 2) compares two parameters used for sorting.

3. Use the following constructor in the main class

TreeSet (Comparator

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report