A collection of Java basics

Source: Internet
Author: User
Tags addall float double

A

The collection class is located in the JDK Java.util package.

Common collection types are distributed across the java.util.Collection and JAVA.UTIL.MAP interfaces. java.util.collection=>list; java.util.collection=>set; Java.util.Map;

Note: In Java inheritance, subclasses can inherit from the parent class, and the same subinterface can inherit the parent interface to augment the functionality of the sub-interface.

  List:

1, the basic concept first, the list is a variable length

2, second, the list can store a variety of data types, but limited to reference types, and then the list is ordered, which can be accessed by subscript.

3, using the list can not be directly instantiated (list is the interface type), by instantiating his implementation class (ArrayList, LinkedList).

In Java's basic data types, they all have a corresponding reference type (Package Class) Int=>integer float=>float double=>double char=>character boolean=> Boolean Long=>long

  ArrayList and LinkedList:

1, ArrayList we usually become the variable-length array, first it maintains its own order through the subscript index, uses the natural sort. The advantage is the ability to quickly iterate through all of the data elements in the collection, or you can get to the specified element through the subscript index. Since the order in which the index is maintained is used to maintain the collection, once the data structure in the collection changes (insertions, deletions), the original collection structure changes and the subscript index needs to be rewritten. Therefore, in the premise of frequent operation of the set, the preferred choice of LinkedList.

2. LinkedList we usually become a list of queues. We use this collection object to implement the stack, the queue. Provides a more convenient way to insert, delete (queue head, tail), you can implement FIFO, or can achieve LIFO. An operation indexed in a list traverses the list from the beginning or end (from one end near the specified index).

3, the list of the iteration of the list, we can use the iterator () method to produce an iterator object, the original list of the contents of the collection as an iterative way to find and traverse. It differs from list in that the list is traversed in two directions through a special iterator (listiterator), and elements can be inserted and removed from the list.

Because list is a sub-interface of collection, they take enumeration, and the list relies on index bits (subscripts) to maintain the order of the elements in the collection, and once the insert and delete actions are used frequently, the list is re-maintained for each operation. Iterators are used iteratively to insert and delete data more efficiently, and to allow traversal from both ends.

Set:

1, Concept: First, set is a variable-length set type;

2. Duplicate elements are not allowed in set, and once duplicate elements are present, subsequent elements overwrite the previous elements.          then, the elements in the set are unordered, in order of deposit and out of order.

3, the common set implementation class: HashSet, TreeSet. The hashset is not guaranteed to be orderly because of the structure of the hash table, and the TreeSet uses the natural sort.

HashSet and TreeSet:

1. HashSet we generally think of him as unordered (arranged in HashSet according to the hashcode of the elements), thus resulting in an inconsistency between the regular output order and the order placed. Where the content is the integer type, then its hashcode is itself.

2. TreeSet we generally think that it is arranged in a natural order. Note that this sort method is sorted by the size of each element compared to CompareTo (). Where the numbers are in their own size, and the letters are sorted in dictionary order.

Map:

1. Basic concept: Unlike list and set, map does not inherit from collection interface. The structure of Map belongs to the key value pair structure,map<k,v>.

2, basic use we usually use the key in the map to obtain the corresponding value content. Map.get (key); You can also get all the Key,map.keyset () at once, and return a set collection to all Value,map.values () at once; Returns a collection collection.

Two

List class and set class   The list class and set class are sub-interfaces of the collection collection interface.   Set sub-interface: unordered, no repetition allowed. List sub-interface: Ordered, can have repeating elements.

Set and list comparison:    Set: The retrieval element is inefficient, the deletion and insertion efficiency is high, and insertions and deletions do not cause the element position to change. List: And arrays, lists can grow dynamically, find elements efficiently, and insert deleted elements inefficiently because they cause other elements to change position.

Set and list specific subclasses: set | ———— HashSet: Storing elements as a hash table, inserting deletes quickly. List | ———— ArrayList: Dynamic Array | ———— LinkedList: Linked list, queue, stack.

The array and java.util.Vector vectors are an old dynamic array that is thread-synchronized, inefficient, and generally deprecated. So I'm not going to introduce you here.

Thread-Safe collection classes and non-thread-safe collection classes LinkedList, ArrayList, hashset are non-thread-safe, vectors are thread-safe; HashMap is non-thread-safe, Hashtable is thread-safe; StringBuilder is non-thread-safe and StringBuffer is thread-safe.

Set application scenarios for finding and deleting more frequent applications with a large number of elements, set or map is a better choice; ArrayList is suitable for scenes where elements are read by means of a position; LinkedList is suitable for scenes where you want to work or insert a specified position; Vector For scenarios where thread-safe ArrayList are used, the Stack is suitable for a thread-safe LIFO scenario, and HashSet is suitable for storing non-repeating elements that are not required for sorting; TreeSet applies to the storage of non-repeating elements to be sorted; HashMap Suitable for most key-value access scenes; TreeMap is suitable for key-value scenes that need to be sorted and stored.

Common uses of the list collection :

  1. Add (Object obj): Adds the element, returns whether to add the success
  2. Clear (): Clears the elements in the collection
  3. Contains (Object obj): Finds whether an incoming element exists in the collection
  4. Get (int index): Gets the element at the specified position
  5. IsEmpty (): Determines whether the collection is empty
  6. Remove (int index): deletes the element at the specified position and returns the element
  7. Size (): Gets the size of the collection
  8. ToArray (): Convert collection to an array

  Common methods for ArrayList collections:

  1. Public ArrayList (int initialcapacity): Constructs an empty list with the specified initial capacity
  2. Pubilc ArrayList (): Constructs an empty list with an initial capacity of 10
  3. Public ArrayList (collection<> C): Constructs a list of elements that contain the specified Collection. If collection is null, it throws NullPointerException
  4. TrimToSize public void TrimToSize (): Adjusts the capacity of this ArrayList to the current size of the list. Applications can use this action to minimize the storage of ArrayList instances.
  5. Size public int size (): Returns the number of elements in this list.
  6. IsEmpty public boolean IsEmpty (): Returns true If there are no elements in this list
  7. contains Public Boolean contains (Object O): returns true If the specified element is contained in this list
  8. indexOf public int indexOf (Object o): returns the index of the specified element that first appeared in this list, or 1 if the list does not contain elements.
  9. lastIndexOf public int lastIndexOf (Object o): returns the index of the specified element that occurred last in this list, or 1 if the list does not contain an index.
  10. ToArray public object[] ToArray (): Returns an array that contains all the elements in this list, in the appropriate order (from first to last element). Because this list does not maintain any references to the returned array, it will be "safe". (In other words, this method must be assigned a new array). Therefore, the caller is free to modify the returned array. This approach serves as a bridge between the array-based API and the collection-based API.
  11. Get public E get (int index): Returns the element at the specified position in this list
  12. Set public E set (int index, E Element): Replaces the element at the specified position in this list with the specified element. The return value is the element that was previously at that specified position
  13. Add public boolean Add (E Element): Adds the specified element to the tail of this list. Add successful return True
  14. Add public void Add (int index, E Element): Inserts the specified element into the specified position in this list. Moves the element that is currently at that position (if any) and all subsequent elements (indexed by 1) to the right.
  15. Remove public E Remove (int index): Removes the element from the specified position in this list, returning the element removed from the list
  16. Remove public boolean remove (Object O) removes the first occurrence of the specified element (if present) in this list. If the list does not contain this element, the list does not change.
  17. Clear public void Clear (): Removes all elements from this list. When this call returns, the list will be empty
  18. AddAll public boolean AddAll (Collection c) adds all elements in the Collection to the end of this list in the order of elements returned by the specified Collection iterator
  19. AddAll public boolean addall (int index, Collection c) Inserts all elements from the specified Collection into this list, starting at the specified position.
  20. RemoveRange protected void RemoveRange (int fromIndex, int endIndex); Remove the index from the list in FromIndex(including) and Toindex all elements between (not included). Moves all subsequent elements to the left (decreasing their index). This call shortens the list of (toindex-fromindex) elements. (If toindex==fromindex, this operation is not valid.) )

LinkedList Common methods:

  1. Public LinkedList ():--Generate empty linked list
  2. Public LinkedList (Collection col): copy constructor
  3. Public boolean add element: Add a single element
  4. public boolean Add (int index, Object Element) specifies the location to add elements: add a single element
  5. chain list originally stack or queue to handle: < Span class= "Apple-converted-space" > public boolean AddFirst (Object Element)      public Boolean addlast (Object Element)
  6. Clear (): Delete all elements: empty

Set: Common methods

  1. add(E e) : Add this element (optional) If the specified element is not already present in the set.
  2. clear(): Removes all the elements in this set (optional operation).
  3. contains(Object o): Returns trueif the set contains the specified element.
  4. equals(Object o): Compares the equality of the specified object to this set.
  5. isEmpty(): Returns trueif the set contains no elements.
  6. remove(Object o): If the specified element exists in the set, it is removed (optional action).
  7. size(): Returns the number of elements in the set (its capacity).
  8. toArray(): Returns an array that contains all the elements in the set.

Map: Common methods

  1. clear(): Removes all mapping relationships from this mapping (optional operation).
  2. containsKey(Object key): Returns trueif this map contains a mapping relationship for the specified key.
  3. equals(Object o): Compares whether the specified object is equal to this mapping.
  4. get(Object key): Returns the value mapped by the specified key, or returns if the mapping does not contain a mapping for the key null .
  5. isEmpty(): Returns trueif the mapping does not contain a key-value mapping relationship.
  6. keySet(): Returns a view of the keys contained in this map Set .
  7. put(K key, V value): Associates the specified value with the specified key in this map (optional operation).
  8. remove(Object key): If there is a mapping relationship for a key, it is removed from this mapping (optional operation).
  9. size(): Returns the number of key-value mapping relationships in this map.
  10. UEs (): Returns a view of the values contained in this map Collection .

A collection of Java basics

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.