List, Set, Map of the differences and relations (finishing)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https: //blog.csdn.net/zhangqunshuai/article/details/80660974
please indicate the source: Java collection List, Set, and Map, etc. Detailed collection system (the most complete history)
Overview:
List, Set, Map are interfaces, the first two to inherit the Collection interface, Map independent interfaces
have HashSet under Set, LinkedHashSet, TreeSet
has ArrayList under List, Vector, LinkedList
has under Map Hashtable, LinkedHashMap, HashMap, TreeMap
under the Collection interface there is a Queue Interface there PriorityQueue class


Note:
Queue interface List, Set the same level, they are inherited the Collection interface.
Figure you will find, LinkedList can either implement the Queue interface, can be realized List interface. But it, LinkedList implements the Queue interface. Queue Interface narrowing the access to the LinkedList methods (ie parameter type in the method if a Queue, Queue access method can only be completely defined by the interface, but can not directly access non Queue method of LinkedList), so that only appropriate methods can be used.

SortedSet is an interface inside it (only this one TreeSet implementation is available) the elements must be ordered.

Summary:
Connection Interface:
- List orderly, repeatable

ArrayList
advantages: the underlying data structure is an array, the query fast, slow additions.
Disadvantages: thread-safe, high efficiency
Vector
advantages: the underlying data structure is an array, query fast, slow additions and deletions.
Disadvantages: thread-safe, low efficiency
LinkedList
advantages: the underlying data structure is the list, slow queries, additions and deletions fast.
Disadvantages: thread-safe, high efficiency
-Set disorder, the only

HashSet
underlying data structure is a hash table. (Unordered only)
how to ensure the uniqueness of the elements?
1. relies on two methods: hashCode () and equals ()

LinkedHashSet
underlying data structure is a linked list and hash tables. (FIFO ordered insertion, the only)
1 by the ordered list of elements to ensure
2. by a hash table to ensure that the only elements

TreeSet
underlying data structure is a red-black tree. (The only ordered)
1. Sort the elements of how to ensure it?
Natural order
comparator sort
2. How to ensure the uniqueness of the elements?
Determined based on a comparison of the return value is 0

Collection collection for us in the end who use it? (Master)

The only right?

Is: Set

Sort it?

They are: TreeSet or LinkedHashSet
No: HashSet
if you know Set, but do not know which Set, to use HashSet.

No: List

To secure?

Is: Vector
No: ArrayList or LinkedList

Multi-query: ArrayList
additions and more: LinkedList
if you know the List, but do not know which List, to use ArrayList.

If you know Collection collection, but do not know who to use, use ArrayList.
If you know a collection, use ArrayList.

Having a Collection, to simply look Map.

Map Interface:
Above:


Map interface has three more important to realize categories, namely HashMap, TreeMap and HashTable.

TreeMap is ordered, HashMap and HashTable are unordered.
Hashtable methods are synchronized, the method HashMap is not synchronized. This is the main difference between the two.
This means:

Hashtable is thread-safe, HashMap is not thread safe.
HashMap high efficiency, low Hashtable efficiency.
If no synchronization requirements for compatibility with legacy code or recommended HashMap. Hashtable view the source code can be found, in addition to the constructor, declare all public methods of the Hashtable are synchronized keyword, while HashMap is not the source code.
Hashtable does not allow null values, HashMap allows null values (key and value are allowed)
different parent class: Hashtable class is the parent Dictionary, HashMap parent is AbstractMap
key issues focuses on:
(a) .TreeSet, the difference LinkedHashSet and HashSet
1 Introduction

TreeSet, LinkedHashSet and HashSet are implemented in java data structure of a Set
main function for sorting TreeSet
primary function for ensure LinkedHashSet i.e. ordered set FIFO (First In First Out)
HashSet simply a collection of general-purpose data storage
2. Same point

Duplicates elements: because all three to achieve Set interface, so do not include the three Elements Duplicate
the Thread Safety: the three are not thread-safe, if you want to use thread-safe can Collections.synchronizedSet ()
3. difference

Performance and Speed: HashSet insert data the fastest, followed by LinkHashSet, the slowest since the internal implementation TreeSet sort
Ordering: HashSet does not guarantee an orderly, LinkHashSet ensure FIFO that is sorted in order of insertion, the internal implementation sort TreeSet installation, you can also customize sorting rule
null: HashSet and allowed LinkHashSet null data, but will be reported NullPointerException null data inserted when a TreeSet
4. Comparative Code

public static void main(String args[]) {
HashSet<String> hashSet = new HashSet<>();
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
TreeSet<String> treeSet = new TreeSet<>();

for (String data : Arrays.asList("B", "E", "D", "C", "A")) {
hashSet.add(data);
linkedHashSet.add(data);
treeSet.add(data);
}

// do not ensure the orderly
System.out.println ( "Ordering in HashSet:" + hashSet);

// FIFO ensure sequential ordering mounting insert
System.out.println ( "Order of element in LinkedHashSet :" + linkedHashSet);

// Internal implements sorting
System.out.println ( "Order of objects in TreeSet :" + treeSet);


}
Run Results:
Ordering in HashSet: [A, B, C, D, E] (not sequentially)
the Order of Element in a LinkedHashSet: [B, E, D, C, A] (insert the FIFO order)
the Order of Objects in TreeSet: [A, B, C , D, E] ( sort)

(Ii) .TreeSet two sort Comparative
incorporated 1. sorting (sorting basic data types for example)
because TreeSet sort elements may be implemented according to certain rules, such as the following example

public class MyClass {

static void main public (String [] args) {
// create a collection of objects
sorted order // Nature
TreeSet <Integer> ts = new TreeSet <Integer> ();

// Create and add an element
// 20,18,23,22,17,24,19,18,24
ts.add (20);
ts.add (18);
ts.add (23);
ts.add ( 22 is);
ts.add (. 17);
ts.add (24);
ts.add (. 19);
ts.add (18 is);
ts.add (24);

// 遍历
for (Integer i : ts) {
System.out.println(i);
}
}
}

The results:
. 17
18 is
. 19
20 is
22 is
23 is
24

? 2. If it is a reference data types, such as custom objects, how to sort it
test class:

public class MyClass {
public static void main(String[] args) {
TreeSet<Student> ts=new TreeSet<Student>();
//创建元素对象
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 objects to the collection element object
ts.add (S1);
ts.add (S2);
ts.add (S3);
ts.add (S4);
ts.add (S5);
ts.add (S6 );

//遍历
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;
}
}

The results given:


Analysis:
without knowing the security sort as that in the sorting, it will be given.
Solution:
1. Natural sort
2. Sort comparator

. (1) natural order
natural order to do the following operations:
1.Student classes implement Comparable interface
2. Method override Comparable interface Compareto

compareTo (T o) Compare this object with the specified object.
. 1
public class Student the implements the Comparable <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;
}

@Override
public int the compareTo (Student S) {
// return -1; // -. 1 represents a red-black tree on the left side, i.e., reverse output
// return 1; // 1 represents a red-black tree on the right side, i.e., sequentially outputs
// return o; // denote the same elements, only the first storage element
// length of the primary condition name, if the name of a small length is on the left sub-tree, or on the right subtree
int num = this. name.length () - s.name.length ();
the same // name length, does not represent the same contents, if before this string object lexicographically parameter string is located, the comparison result is a negative integer.
// If after this String object lexicographically parameter string is located, the comparison result 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 same name // length and content, does not mean the same age, so but also to determine the age
int num2 = num1 == 0 this.age-s.age:? num1;
return num2;
}
}

operation result:

November 22 -----------
Qianqi ----------- 24
Wangwu ----------- 24
chenliu ---------- -26
zhangsan ----------- 20
zhangsan ----------- 22

(2) ordering the comparator.
The comparator sorting steps:
1. Create a separate class comparison, as an example here for MyComparator, and let its successor Comparator interface
Compare method 2. Comparator interface rewritable

compare (T o1, T o2) for comparing two parameters sorted.
1
3. The method of using the following configurations in the main category

TreeSet (Comparator <? SuperE> comparator )
Constructs a new empty TreeSet, it is sorted according to specified comparator.
. 1
2
Test categories:

public class MyClass {

static void main public (String [] args) {
// create the collection object
// TreeSet (Comparator <? super E > comparator) Constructs a new empty TreeSet, it is sorted according to specified comparator.
TreeSet <Student> ts = new TreeSet <Student> (new MyComparator ());

//创建元素对象
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 objects to the collection element object
ts.add (S1);
ts.add (S2);
ts.add (S3);
ts.add (S4);
ts.add (S5);
ts.add (S6 );

//遍历
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;
}

}

MyComparator categories:

public class MyComparator implements Comparator<Student> {

@Override
public int Compare (Student S1, S2 Student) {
// name length
int NUM = s1.getName () length () - s2.getName () length ();..
// name of content
int num2 = num == ? 0 s1.getName () compareTo (s2.getName ()): NUM;.
// Age
int num2 num3 = == 0 s1.getAge () - s2.getAge ():? num2;
return num3;
}

}

The result:

November 22 -----------
Qianqi ----------- 24
Wangwu ----------- 24
chenliu ---------- -26
zhangsan ----------- 20
zhangsan ----------- 22

. (C) performance test
object classes:

class Dog implements Comparable<Dog> {
int size;
public Dog(int s) {
size = s;
}
public String toString() {
return size + "";
}
@Override
public int compareTo(Dog o) {
//数值大小比较
return size - o.size;
}
}

主类:

public class MyClass {

public static void main(String[] args) {

Random r = new Random();
HashSet<Dog> hashSet = new HashSet<Dog>();
TreeSet<Dog> treeSet = new TreeSet<Dog>();
LinkedHashSet<Dog> linkedSet = new LinkedHashSet<Dog>();

// start time
long startTime = System.nanoTime();
for (int i = 0; i < 1000; i++) {
int x = r.nextInt(1000 - 10) + 10;
hashSet.add(new Dog(x));
}

// end time
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println("HashSet: " + duration);

// start time
startTime = System.nanoTime();
for (int i = 0; i < 1000; i++) {
int x = r.nextInt(1000 - 10) + 10;
treeSet.add(new Dog(x));
}
// end time
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("TreeSet: " + duration);

// start time
startTime = System.nanoTime();
for (int i = 0; i < 1000; i++) {
int x = r.nextInt(1000 - 10) + 10;
linkedSet.add(new Dog(x));
}

// end time
endTime = System.nanoTime();
duration = endTime - startTime;
System.out.println("LinkedHashSet: " + duration);
}

}


operation result:

HashSet: 1544313
TreeSet: 2066049
LinkedHashSet: 629 826
Although the test is not accurate enough, but it can come to reflect, TreeSet much slower, because it is ordered.

 

Well, to this end. Junior partner have questions, please leave a message

Guess you like

Origin www.cnblogs.com/dblb/p/11470556.html