Java Collection Framework Study Notes_Summary

The origin of the collection class:
Objects are used to encapsulate unique data. If there are more objects, they need to be stored. If the number of objects is uncertain.
Just use a collection container for storage.

Collection features:
1. A container for storing objects.
2. The length of the set is variable.
3. Basic data type values ​​cannot be stored in the collection.

Collection containers have a variety of specific containers because of different internal data structures.
Continuous upward extraction forms a collection framework.

The framework's top-level Collection interface:

Common methods of Collection:

1,添加。
boolean add(Object obj):
boolean addAll(Collection coll):

2,删除。
boolean remove(object obj):
boolean removeAll(Collection coll);
void clear();

3. Judgment:
boolean contains(object obj):
boolean containsAll(Colllection coll);
boolean isEmpty(): judge whether there is an element in the collection.

4. Get:
int size():
Iterator iterator(): The way to take out elements: iterator.
The object must depend on the concrete container, because the data structure of each container is different.
So the iterator object is implemented internally in the container.
For the user of the container, the specific implementation is not important, as long as the object of the iterator of the implementation can be obtained through the container,
that is, the iterator method.

Iterator接口就是对所有的Collection容器进行元素取出的公共接口。
其实就是抓娃娃游戏机中的夹子!

5. Others:
boolean retainAll(Collection coll); Take the intersection.
Object[] toArray(): Convert the collection to an array.


Collection
|–List: Ordered (the order of storage and retrieval is the same), elements have indexes (angular labels), and elements can be repeated.
|–Set: Elements cannot be repeated, unordered.

List: Unique common method: There is a common feature that all can operate the corner mark.

1,添加
void add(index,element);
void add(index,collection);

2. Delete;
Object remove(index):

3. Modify:
Object set(index,element);

4,获取:
Object get(index);
int indexOf(object);
int lastIndexOf(object);
List subList(from,to);

The list collection can complete the addition, deletion and modification of elements.

List:
|–Vector: Internally is an array data structure, which is synchronized. Additions and deletions, queries are very slow!
|–ArrayList: The internal is an array data structure, which is asynchronous. Replaces Vector. The query speed is fast.
|–LinkedList: The internal is a linked list data structure, which is asynchronous. Elements are added and removed very quickly.

LinkedList:

addFirst();
addLast():
jdk1.6
offerFirst();
offetLast();


getFirst();.//获取但不移除,如果链表为空,抛出NoSuchElementException.
getLast();
jdk1.6
peekFirst();//获取但不移除,如果链表为空,返回null.
peekLast():

removeFirst();//获取并移除,如果链表为空,抛出NoSuchElementException.
removeLast();
jdk1.6
pollFirst();//获取并移除,如果链表为空,返回null.
pollLast();

Homework:
1. Check the documentation to demonstrate the elements() method in Vector.

2,LinkedList中的,addFirst addLast getFirst,getLast removeFirst removeLast。

3. Since the collection is for storing objects, please define the ArryaList collection and store the Person object. Such as new Person("lisi", 20);
and take it out. Print your name and age.


Set: Elements cannot be repeated and are unordered.
The methods in the Set interface are consistent with Collection.
|–HashSet: The internal data structure is a hash table, which is not synchronized.
How to ensure the uniqueness of the elements of the set?
Object uniqueness is accomplished through the object's hashCode and equals methods.
If the hashCode values ​​of the objects are different, they are stored directly in the hash table without judging the equals method.
If the hashCode value of the object is the same, then it is necessary to judge again whether the equals method of the object is true.
If true, it is regarded as the same element and does not exist. If false, it is treated as a different element and stored.

    记住:如果元素要存储到HashSet集合中,必须覆盖hashCode方法和equals方法。
    一般情况下,如果定义的类会产生很多对象,比如人,学生,书,通常都需要覆盖equals,hashCode方法。
    建立对象判断是否相同的依据。




|--TreeSet:可以对Set集合中的元素进行排序。是不同步的。 
            判断元素唯一性的方式:就是根据比较方法的返回结果是否是0,是0,就是相同元素,不存。 

            TreeSet对元素进行排序的方式一:
            让元素自身具备比较功能,元就需要实现Comparable接口。覆盖compareTo方法。

            如果不要按照对象中具备的自然顺序进行排序。如果对象中不具备自然顺序。怎么办?
            可以使用TreeSet集合第二种排序方式二:
            让集合自身具备比较功能,定义一个类实现Comparator接口,覆盖compare方法。
            将该类对象作为参数传递给TreeSet集合的构造函数。

if(this.hashCode()== obj.hashCode() && this.equals(obj))

The hash table determines whether the elements are the same
1, and judges whether the hash values ​​of the two elements are the same.
If it is the same, it is judged whether the contents of the two objects are the same.

2. Judging that the hash value is the same, in fact, it is the method of judging the hashCode of the object. To determine the same content, the equals method is used.

Note: If the hash values ​​are different, there is no need to judge equals.


Generics:
The security mechanism that appeared in jdk1.5.

Benefits:
1. The runtime problem ClassCastException is transferred to compile time.
2, to avoid the trouble of forced conversion.

<>: When to use? When the reference data type of the operation is indeterminate. Just use <>. Just pass in the reference data type to be operated.
In fact, <> is a parameter range used to receive a specific reference data type.

In the program, as long as the class or interface with <> is used, the specific reference data type passed in must be specified.

Generics techniques are techniques used by the compiler at compile time. Type safety is ensured.

When running, the generics will be removed, and the generated class files will not contain generics, which is called generic erasure.
Why erase it? Because for compatibility with running classloaders.

Generic compensation: At runtime, the conversion action is performed by obtaining the type of the element. There is no need for the user to force the conversion.

Wildcards for generics: ? Unknown type.

Restrictions on generics:
? extends E: Receives an object of type E or a subtype of E. The upper limit
is generally used when storing objects. For example, adding the element addAll.

? super E: Receives an object of type E or supertype of E. lower limit.
It is generally used when removing objects. such as comparators.

===========================================================

Some tips for collections:

Need unique?
Need: Set
needs to be ordered:
Need: TreeSet
does not need: HashSet
but want a consistent order (ordered) with storage: LinkedHashSet
does not need: Does List
need to be added or deleted frequently?
Required: LinkedList Not
Required: ArrayList

How to record the structure and belonging system of each container?

Look at the name!

List
|–ArrayList
|–LinkedList

Set
|–HashSet
|–TreeSet

The suffix name is the system to which the collection belongs.

The prefix name is the data structure of the collection.

When you see an array: you must think of an array, you must think of a fast query, and there are corner labels.
When you see a link, you must think of a linked list, you must think of adding and deleting fast, you must think of the method of add get remove+frist last
See hash: When you think of hash tables, you must think of uniqueness, and you must think of elements that need to override the hashcode method and the equals method.
When you see a tree: you have to think of a binary tree, you have to sort it, you have to think of two interfaces Comparable, Comparator.

And usually these commonly used collection containers are not synchronized.

============================================

Map: Adds a pair of elements at a time. Collection adds one element at a time.
Map is also called a two-column collection, and a Collection collection is called a single-column collection.
In fact, the map collection stores key-value pairs.
The uniqueness of keys must be guaranteed in the map collection.

Common methods:
1. Add.
value put(key,value): Returns the previous value associated with key, or null if not.

2. Delete.
void clear(): Clears the map collection.
value remove(key): Flip out the key-value pair according to the specified key.

3,判断。
boolean containsKey(key):
boolean containsValue(value):
boolean isEmpty();

4. Get.
value get(key): Get the value by key, or return null if there is no such key.
Of course, you can return null to determine whether the specified key is included.
int size(): Get the number of key-value pairs.

Commonly used subclasses of Map:
|–Hashtable : The internal structure is a hash table, which is synchronized. Null is not allowed as key and null as value.
|–Properties: Used to store key-value pair configuration file information, which can be combined with IO technology.
|–HashMap : The internal structure is a hash table, not synchronized. Allow null as key and null as value.
|–TreeMap : The internal structure is a binary tree, not synchronized. The keys in the Map collection can be sorted.

List list = new ArrayList();//Asynchronous.

list = MyCollections.synList(list);//Return a synchronized list.

Locks an asynchronous collection.

class MyCollections{

public static  List synList(List list){

    return new MyList(list);
}

private class MyList implements List{
private List list;

private static final Object lock = new Object();
MyList(List list){  
    this.list = list;   
}

public boolean add(Object obj){
    synchronized(lock)
    {
        return list.add(obj);
    }
}

public boolean remove(Object obj){
    synchronized(lock)
    {
        return list.remove(obj);
    }
}

}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324587439&siteId=291194637