Javase Collection---Progress 2

Source: Internet
Author: User
Tags addall comparable int size set set

I. Set frame

1. Features

Objects encapsulate data, objects need to be stored, and collections are used to store objects.

The number of objects determines that the array can be used, but if you are unsure, you can use the collection because the collection is variable-length.

2. Differences between sets and arrays

Arrays are fixed-length, and collections are variable-length.

Arrays can store basic data types, or they can store reference data types, and collections can store only reference data types.

The elements stored in an array must be of the same data type, and the objects stored by the collection can be of different data types.

3. Data structure

For collection containers, there are many kinds. Because each container's own characteristics are different, in fact, the principle is that each container internal data structure is different, the collection container in the continuous upward extraction process. There is a collection system.

Second, collection interface

1.List: Ordered (the access order of the elements does not change), the elements are indexed, and the elements can be duplicated.

2.Set: unordered, cannot store duplicate elements, stored elements are unique.

Methods in the 3.Collection interface

Add to:

Add (object): Adds an element

AddAll (Collection): Add a Collection

Delete:

Clear (): Clears the collection and removes all the collection elements.

Remove (obj): Deletes a single element.

RemoveAll (collection): Deletes a partial element, which is the deletion of the specified subset.

Judge:

Boolean contains (obj): Determines whether an element is included.

Boolean contains (collection): Determines whether a collection is included.

Boolean isEmpty (); The collection is sentenced to null.

Get:

int size (): Returns the number of elements.

To take the intersection:

Boolean Retainall (Collection): A.retainall (B); AB takes the intersection. If a set has a change, the general element will be less, if not changed, that is, the set AB element is the same, the return value is false; otherwise it returns true;

Gets all the elements in the collection:

Iterator Iterator (): iterator

To turn a collection into an array:

ToArray ();

Third, iterator interface:

Boolean Hasnext (), iteration condition, empty condition.

E next (), which returns the next element of the iteration.

void Remove () removes the last element returned by the iterator from the collection that the iterator points to.

public static void Main (string[] args) {

Collection coll = new ArrayList ();

Coll.add ("abc0");

Coll.add ("ABC1");

Coll.add ("ABC2");

Iterator it = Coll.iterator ();

while (It.hasnext ()) {

Syso (It.next ());

}

}

for (Iterator it = Coll.iterator (); It.hasnext ();) {

Syso (It.next ());

}

Iv. List Interface

1.

The list itself is a sub-interface of the collection interface and has all the collection methods. Now learning the common method peculiar to list system, the method of lookup finds that the unique method of list has index, which is the most characteristic of this set.

2.

List: Ordered (the order in which the elements are stored in the collection is consistent with the order taken). Elements are indexed and can be duplicated.

ArrayList: The underlying data structure is an array, the thread is out of sync, the ArrayList replaces the vector, and the query element is fast.

LinkedList: The underlying data structure is linked list, the thread is not synchronized, adding or deleting elements is very fast.

Vector: The underlying data structure is an array, thread synchronization, the vector regardless of query and additions and deletions are relatively slow.

Add to:

Add (index,element): Inserts an element at the specified index position.

AddAll (index,collection): Inserts a collection at the specified index location.

Delete:

Remove (Index): Removes the element at the specified index position. Returns the element that was deleted.

Get:

Object Get (Index): Returns the element at the specified position.

int indexOf (obj): Gets the position of the first occurrence of the specified element, returns 1 if the element does not exist;

int lastIndexOf (OBJ): Returns the position of the last occurrence of the specified element.

List sublist (start,end): Gets the child list.

Modify:

Set (index,element): Modifies elements of the specified index.

Get all elements:

Listiterator Listiterator (): A list collection-specific iterator.

2.1

Listiterator is a sub-interface of iterator and is a list-specific iterator

ListIterator IT= list.listiterator;

 

add(E e) Inserts the specified element into the list (optional action).

 boolean

hasNext() Returns trueif the list iterator has more than one element when traversing the list in a forward direction (in other words, trueif next returns an element instead of throwing an exception).

 boolean

hasPrevious() Returns trueif the list iterator has more than one element in the reverse loop.

 E

next() Returns the next element in the list.

 int

nextIndex() Returns the index of the element returned by subsequent calls to next .

 E

previous() Returns the previous element in the list.

 int

previousIndex() Returns the index of the element returned by subsequent calls to previous .

 void

remove() Removes the last element returned by next or previous (optional action) from the list.

 void

set(E e) Replaces the last element returned by next or previous with the specified element (optional action).

2.2

LinkedList: A unique approach

AddFirst (); AddLast ();

After jdk1.6, there was Offerfirst (); Offerlast ();

GetFirst (): Gets the first element in a linked list. GetLast (); Gets the last element in the list.

After jdk1.6, there are Peekfirst (), and Peeklast ();

Removefirst ()/removelast (), deletes and returns the Kinsoku element.

After jdk1.6, there is Pollfirst ()/polllast ();

Five, set interface

The method in the set interface is consistent with the method in collection, and the set interface is removed in only one way, an iterator.

1.

HashSet: The underlying data structure is a hash table, and threads are not synchronized. Disorderly, efficient.

HashSet Collection guarantees element uniqueness: By means of the Hashcode method of the element, and by the Equals method, when the element's Hashcode value is the same, the equals of the element is determined to be true, and if the hashcode value is different, the equals is not judged , which increases the speed of object comparisons.

Linkedhashset: Ordered, HashSet sub-class.

TreeSet: The ordering of the specified order of elements in the set collection. In different steps, the data structure of the treeset is a binary tree.

2, the principle of the hash table:

For the keywords in the object element (unique data in the object), the hash algorithm is computed and a specific algorithm value is obtained, which is called the hash value .

The hash value is the position of this element.

If there is a conflict in the hash value, again determine whether the object corresponds to the same keyword. If the objects are the same, they are not stored because the elements are duplicated. If the object is different, it is stored and deferred on the original object's hash value base +1.

The structure that stores the hash value, which we call a hash table.

Since the hash table is stored according to the hash value, it is best to ensure that the object's keywords are unique for efficiency.

This can be as few as possible to determine whether the corresponding object of the same keyword, improve the operation efficiency of the hash table.

For ArrayList sets, it is the Equals method to determine whether an element exists or to delete an element's underlying basis.

For HashSet collections, determine whether an element exists, or delete an element, based on the hashcode and equals methods.

3.TreeSet

Used to sort the specified order of elements in the set collection, and the ordering needs to be based on the comparison of the elements themselves.  If the element is not comparable, a ClassCastException exception occurs at run time.  So we need elements to implement comparable interface, forcing elements to have a comparative, CompareTo method of replication. Based on the return value of the CompareTo method, the method of determining the position of the element in the TreeSet data structure TreeSet methods to guarantee the uniqueness of the element: that is, if the result of the reference comparison method is 0, if return 0 is treated as two objects, it is not saved.

When comparing, if the judgment element is not unique, for example, the same name, the same age, only as the same person.

In the judgement, the main conditions and secondary conditions need to be divided, when the main conditions are the same, then judge the secondary conditions, sorted by the secondary conditions.

Vi. Collection of Maps

1.

Hashtable: The underlying is a hash table data structure that is thread-synchronized. You cannot store null keys, null values.

HashMap: The underlying is also a hash table data structure, which is a thread that is not synchronized and can store null keys, null values.

TREEMAP: The bottom layer is a two-fork tree structure that allows you to sort the keys in the map collection in a specified order.

2.

Add to

Put (Key,value): When the stored key is the same, the new value replaces the old value and returns the old value, if the key is not duplicated, returns null;

void Putall (map);

Delete

void Clear (): Empty

Value Remove (key): Delete the specified key

Judge

Boolean isEmpty ();

Boolean Containkey (key);

Boolean Containvalue (value): Whether the value is included

Remove

int size (): Returns the length.

Get (Key): Gets the corresponding value by specifying the key, and if NULL is returned, you can tell that the key does not exist, or that the value corresponding to the key is null

Collection values (): Gets all the values in the Map collection.

3.

Get all the elements in the map:

principle:There is no iterator in map, collection has an iterator, and as long as the map collection is turned into a set set, an iterator can be used. The reason why the set is transferred is because the map set has the uniqueness of the key, in fact, the set set is derived from the Map,set set at the bottom of its practical is the map method.

3.1

The key in the map collection can be removed and stored in the set collection. Iterates over a set set. The iteration is completed, and then the value of the corresponding key is obtained by the Get method.

Set keyset = Map.keyset ();

Iterator it = Keyset.iterator ();

while (It.hasnext ()) {

Object key = It.next ();

Object value = Map.get (key);

SOP (key+ ":" +value);

}

3.2

The EntrySet collection is obtained through the Map.entryset () method, and a collection of entry relationships is obtained.

Set EntrySet = Map.entryset ();

Iterator it = Entryset.iterator ();

while (It.hasnext) {

Map.entry me = (map.entry) it.next ();

SOP (Me.getkey () + ":" +me.getvalue ());

}

VII, collections and arrays

1.

Static objects,

Collections.sort (lsit);//The list collection is ordered in a natural order.

Collections.sort (List,newcomparatorbylen ());//Sort by the specified comparer method.

Classcomparatobylen Implements comparator<string>{

public int Compare (String s1,string s2) {

int temp = S1.length ()-s2.length ();

return temp = = 0?s1.compareto (s2): temp;

}

}

Collections.max (list);//returns the element with the largest dictionary order in the list.

int index = Collections.bianry.Search (list, "zz");//binary lookup, return corner label

Collections.reverseorder ();//Reverse Reverse sort

Collections.shuffle (list);//random displacement of the position of the elements in the list.

2.

Defines a class that adds a collection of all methods to the same lock.

Collections in the xxxsynchronizedxxx (XXX);

Listsynchronizedlist (list);

Mapsynchronizedmap (map);

3.

Collections is a Java.util class, a tool class for a collection class that provides a set of static methods for operations such as finding, sorting, replacing, threading, and converting non-synchronized collections to synchronous.

Collection is a Java.util interface, which is the parent interface of various collection structures, and the interfaces that inherit from it are mainly set and list, providing some operations on the set, such as inserting, deleting, judging whether an element is its member, traversing, etc.

Arrays

The tool class used to manipulate array objects is a static method.

Aslist method: Converting an array into a Lsit collection

String[] arr = {"abc", "KK", "QQ"};

List<string>list = Arrays.aslist (arr);

The elements in the array can be manipulated through the methods in the list collection: IsEmpty (), contains, indexOf, set;

System.out.println (I1);

Javase Collection---Progress 2

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.