Java collection type (ii)

Source: Internet
Author: User

JAVA collection type (modern variable cluster)

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /center ">

List ( interface )

Characteristics:

A. sequencing is sensitive. LIST elements in the structure must be separated from who first who is behind.

B. Be able to repeat ....

It is mainly used tosimulate thesequence-sensitive application scenarios such as queue.

<1> ArrayList (array-based implementation)

Arrays are cumbersome to use,ArrayList is a class. The array was reconstructed 2 times. or two development based on the data, overcoming the many shortcomings of the array from the angle of use. But in essence, it relies on the array mechanism to complete.

ArrayList internally relies on an array of objects object[], which has many methods. All surround the object array expansion.

Size () gets The number of elements that are actually included inside the ArrayList.

Add () append to last

Add (index,obj) inserts the data to the subscript position specified by index

Remove (index) deletes The element at the specified index position

Remove (obj) deletes the element that matches the object (dependent on equals )

Contains (obj) to see if the element exists

IndexOf (obj) View the index bits that appear on the element (starting from scratch)

LastIndexOf (obj) to view the index bits that appear on the element (from the end to start)

IsEmpty () to see If a valid element exists in ArrayList
Sublist () Create sub List

ToArray () Turn List to Array

TrimToSize reduces the amount of capacity to the actual number of elements that exist.

Strengths:

Similar to arrays, the random positioning speed is very fast .

But in the coding convenience is much better than the array, less write a lot of control code.

Disadvantages:

With array type, insert and delete easy cause large fluctuations. When the force of the element is out of range. There are also large numbers of copies of array elements that occur, which have a significant impact on system performance.

Applicable scenarios:

After data entry. More stable, less delete and insert operations, mostly for location query operations

Data is added in a longer frequency interval and will not be continuously added continuously

A data structure that is extremely sensitive to the sequencing of elements such as queues.

traversal of the ArrayList

1. General Traversal Method

for (int i=0;i<al.size (); i++)

System.out.println (Al.get (i)):

1. Collection type dedicated traversal method (jdk1.5 above version number support )

for (Object Obj:al)

System.out.println (obj);

2. Iterative body (iterator) traversal method

Iterator Itr=al.iterator ();

while (Itr.hasnext ())

System.out.println (Itr.next ());

ArrayList generic type (generic type) control

Because the ArrayList is very flexible, the internal ability to place a variety of data types, resulting in external programs, from the ArrayList to take out an element, it must be carefully inferred, Sometimes the external need for a large number of various types of code to the different objects for the corresponding operation, the cost is high. Some program apes forget to write some code. Often leads to classcastexception, So later, people have to limit the types of elements in ArrayList, requiring only one element within them.

<2> LinkedList ( linked list-based implementation )

Strengths:

With linked list types. Insert and delete performance is superior and does not cause memory fluctuations.

Disadvantages:

Similar to a linked list. The random positioning speed is slow, you need to start from the beginning to retrieve .

High memory consumption of the linked list

Applicable scenarios:

After data entry. More unstable, with frequent deletion and insertion operations, random location query relatively few.

A data structure that is extremely sensitive to the sequencing of elements such as queues.

2. Set(interface)

Characteristics:

1. Set is a sub-interface of the Collection interface, which inherits All the abstract methods in the Collection interface. The method extension for Set application is also done.

2. the Set interface emphasizes non-repetition, but no sequencing.

A. HashSet

The type of collection for which the data is stored according to the hash ( hash ) algorithm for the memory allocation, and for the elements in which it is loaded. The location where the memory is saved. Users do not care. The way to save is certainly efficient, which is guaranteed with a hashing algorithm, but there is one point that cannot be repeated! For elements inserted in. HashSet does not guarantee its sequencing.

HashSet How to identify the elements that are inserted?

? Understanding Object.hashcode ()

The object has a hashcode method, which is a local method, implemented by the C language, and returns the start address of the object in memory. The return value is an integer.

No matter what object assumes that it does not override the hashcode method of object . Then the values of the hashcode are different.

? HashSet relies on The return value of hashcode to infer whether the object is equal

1. When an object is attempted to be saved intoHashSetthe time,HashSetThis object will be called first.hashcodemethod returns ahashcodevalues,HashSetThe value and its internalhashcodeList(The table holds all of the savedHashSetOf the object in thehashcodevalue)To do the comparison, If you find that there is no same, you feel that the objectHashSetis not repeated, can be accepted.

2. Suppose that the hashcode of an object is identical to an object in the list. Then hashset will invoke the object's equals method to see if the same is finally inferred. Equals feels different, andhashset will still accept the object.

Object has the equals and hashcode Two methods to infer whether the object content is equal, in a common application. In general, we can infer with equals, but hashset because it needs to remain the same in nature, so it often does the same thing with the object, because the collection type is very demanding for performance. the equals inference involves more complex logic. The cost is very high. Performance is reduced to some extent, but equals inference is the most accurate inference .

From a performance standpoint,Object also provides a lightweight inference method , hashcode. because hashcode The interior is only an integer operation, and the underlying is C , it's very fast.

Hashcode feel not the same. The object is a different object, andequals is not involved.

Hashcode felt the same, then by equals to make the final inference,equals result is Finally, can overthrow The result of Hashcode's decision.

Hashcode is the "District Court" and equals is the "Court of Final Appeal".

? The contract between Hashcode and equals

Because there is a master-slave relationship between the hashcode and the equals method, especially if an object is finally dealing with hashset , You must rewrite the hashcode and equals methods at the same time, and two methods must guarantee a contract when overriding, otherwise the rewrite will fail.

Contract:

1. Hashcode different, equals must be different

2. Hashcode Similarly, equals can be different

B. TreeSet ( tree structure Collection )

The elements inside the TreeSet cannot be repeated. But the sort output will be sorted according to some established rule (natural order).

All objects in the TreeSet must implement the comparable interface.

The interface has only one method, int compartto (obj);

return value:

1 The current object is greater than the incoming object

0 Current object equals incoming object

-1 the current object is less than the incoming object

Java collection type (ii)

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.