Java Basics Collection & arrays

Source: Internet
Author: User
Tags set set

Set,list,map the difference between Java collections is divided into three main types:
    • Set (SET)
    • List (lists)
    • Map (map)
To understand the collection in depth first understand the familiar array: the array is fixed in size, and the same array can hold only the same type of data (base type/reference type), while the Java collection stores and operates a set of data that is not fixed. All Java collections are located in the Java.util package! Java collections can only hold data of reference types and cannot hold basic data types. The difference between a set and an array is simple: (Reference article: "Thinking in Algorithm" 03. Data structure) [HTML]View PlainCopy
  1. <span style="font-family: ' Microsoft Yahei '; font-size:12px;" > There is no collection on Earth (only the array reference C language) but someone wants it, so there 's a collection
  2. Some people want an array that can be automatically expanded, so there's a list
  3. Some people want to have no duplicate arrays, so there's set
  4. Some people want to have automatic sorting of the number of groups, so with treeset,treelist,tree**
  5. And almost all of the collections are implemented on an array basis.
  6. Because a collection is a package made of arrays, the array is always faster than any one set
  7. But any collection, more functionality than the array provides
  8. One: The array declares the type of the element it holds, and the collection does not declare it. This is because the collection stores their elements in object form.
  9. Two: An array instance has a fixed size and cannot be scaled. The collection can dynamically change the size as needed.
  10. Three: An array is a readable/writable data structure--there is no way to create a reading group. However, the collection can be used in a read-only manner using the ReadOnly method provided by the collection. The method returns a read-only version of a collection. </span>

Array is the most efficient of all Java "storage and random access to a series of objects".

1.
High efficiency, but the capacity is fixed and cannot be changed dynamically.
One drawback of array is that it is not possible to determine how many elements are actually stored, and length simply tells us the capacity of the array.

2, Java has a arrays class, specifically used to manipulate the array.
The arrays has a set of static functions,
Equals (): Compares two arrays for equality. Array has the same number of elements, and all corresponding element 22 is equal.
Fill (): Fills the value into the array.
Sort (): Used to sort the array.
BinarySearch (): Looks for elements in a sorted array.
System.arraycopy (): Copy of Array.

If you do not know exactly how many objects you need to write your program, and you need to automatically expand capacity when you are running out of space, you need to use the Container class library, which is not applicable. So we need to use the set. So let's start talking about collections in Java. Collection Category: Collection:list, set
The Map:hashmap, HashTable1.1 Collection Interface collection is the most basic collection interface, declaring a common method that applies to a Java collection (including set and list only). Both Set and list inherit the Conllection,map.

1.1.1 Method of Collection interface: [HTML]View PlainCopy
  1. <span style="font-weight:normal;" >boolean Add (Object o): Adding a reference to an object to the collection
  2. void Clear (): Deletes all objects in the collection, i.e. no longer holds references to those objects
  3. Boolean IsEmpty (): Determines whether the collection is empty
  4. Boolean contains (object O): Determines whether a reference to a particular object is held in the collection
  5. Iterartor iterator (): Returns a Iterator object that can be used to iterate through the elements in the collection
  6. Boolean remove (Object o): Removes a reference to an object from the collection
  7. int size (): Returns the number of elements in the collection
  8. Object[] ToArray (): Returns an array that includes all the elements in the collection </span>

About: The Iterator () and ToArray () methods are used for all elements of a collection, which returns an Iterator object that returns an array containing all the elements in the collection. The 1.1.2 Iterator interface declares the following methods: [HTML]View PlainCopy
    1. Hasnext (): Determines whether the elements in the collection are traversed, and if not, returns true
    2. Next (): Returns the next element
    3. Remove (): Removes the last element returned from the collection with the next () method.

1.2 Set (set) is the simplest set. The objects in the collection are not sorted in a particular way, and there are no duplicate objects. The set interface mainly implements two implementation classes:
    • The Hashset:hashset class accesses the objects in the collection according to the hashing algorithm, and the access speed is relatively fast.
    • The Treeset:treeset class implements the SortedSet interface and is able to sort the objects in the collection.
Set usage: Holds reference to object, no duplicate object
    1. Set set=New HashSet ();
    2. String s1=new string ("Hello");
    3. String s2=s1;
    4. String s3=new String ("World");
    5. Set.add (S1);
    6. Set.add (S2);
    7. Set.add (S3);
    8. System.out.println (Set.size ());  the number of objects in the//print collection is 2.

How does the Add () method of Set determine if an object has been stored in the collection?

    1. Boolean isexists=false;
    2. Iterator Iterator=set.iterator ();
    3. while (It.hasnext ()) {
    4. String Oldstr=it.next ();
    5. if (Newstr.equals (OLDSTR)) {
    6. Isexists=true;
    7. }
    8. }

function method of Set

The set has exactly the same interface as the collection, so there is no additional functionality, unlike the previous two different lists. In fact set is collection, but behaves differently. (This is a typical application of inheritance and polymorphic thinking: behavior that behaves differently.) Set does not save duplicate elements (more responsible for how the elements are judged)

Set: Each element that is stored in the set must be unique because set does not save duplicate elements. The element that joins the set must define the Equals () method to ensure the uniqueness of the object. The set has exactly the same interface as the collection. The set interface does not guarantee the order in which elements are maintained.

    • HashSet: Set for quick find design. The object that is deposited into the hashset must define HASHCODE ().
    • TreeSet: The set of the save order, the underlying tree structure. Use it to extract ordered sequences from the set.
Linkedhashset: has hashset query speed, and internally uses the chain list to maintain the order of elements (the Order of insertions). The result is displayed in the order in which the elements are inserted when iterating through the set using Iterators.


The 1.3 list list is characterized by its elements being stored in a linear fashion, where duplicate objects can be stored in the collection.

The main implementation classes of the list interface are: (Reference article: ArrayList and LinkedList)
    • ArrayList (): Represents the length can be changed by the group. Elements can be randomly accessed, and it is slow to insert and delete elements into ArrayList ().
    • LinkedList (): A linked list data structure is used in the implementation. Fast insertion and deletion, and slow access times.
For random access to a list, it is just random to retrieve the element at a particular location. The Get (int index) method of the List returns the object in the collection at the index location specified by the parameter index, starting with "0". The two most basic ways to retrieve all objects in a collection are:


1:for Loop and Get () method:

    1. for (int i=0; I<list.size (); i++) {
    2. System.out.println (List.get (i));
    3. }

2: Using Iterators (Iterator):

    1. Iterator It=list.iterator ();
    2. while (It.hashnext ()) {
    3. System.out.println (It.next ());
    4. }

function method of List


There are actually two kinds of lists: One is the basic ArrayList, the advantage is the random access element, the other is the more powerful linkedlist, it is not for the fast random access design, but has a more general method.

    • List: Order is the most important feature of the list: it ensures that the elements are maintained in a specific order. The list adds a number of methods to collection, allowing you to insert and remove elements to the middle of the list (this is recommended for linkedlist use only. A list can generate Listiterator, which can be used to traverse a list in two directions or to insert and remove elements from the middle of a list.
    • ArrayList: A list implemented by an array. Allows fast random access to elements, but inserts and removes elements in the middle of the list is slow. Listiterator should only be used to traverse the ArrayList backward, not to insert and remove elements. Because that's much more expensive than linkedlist.
    • LinkedList: Sequential access is optimized, and the cost of inserting and deleting to the list is small. Random access is relatively slow. (use ArrayList instead.) ) also has the following methods: AddFirst (), AddLast (), GetFirst (), GetLast (), Removefirst (), and Removelast (), which are not defined in any interface or base class Enables LinkedList to be used as stacks, queues, and bidirectional queues.

1.4 Map (map)

Map is a collection of key object and value object mappings, each of which contains a pair of key objects and value objects. Map does not inherit from the collection interface when retrieving elements from the map collection, the corresponding value object is returned whenever the key object is given.

Common methods of Map:

1 Add, delete operation:

[HTML]View PlainCopy
    1. Object put (object key, Object value): Adding elements to the collection
    2. Object remove (Object key): Delete the element associated with key
    3. void Putall (Map t): Adds all elements from a specific image to the image
    4. void Clear (): Remove all mappings from the image

2 Query operation:

Object get (Object key): Gets the value associated with the keyword key. The key object in the Map collection does not allow duplicates, which means that any two key objects that are compared by the Equals () method are false. But you can map any number of keys to the same value object.

function method of Map

Method put (Object key, object value) adds a "value" (What you Want) and the "Key" (key) associated with the value (using it to find). Method get (Object key) returns the value associated with the given "key". You can test whether a "key" or "value" is included in the map with ContainsKey () and Containsvalue (). The standard Java class library contains several different map:hashmap, TreeMap, Linkedhashmap, Weakhashmap, and Identityhashmap. They all have the same basic interface map, but the behavior, the efficiency, the sorting strategy, the life cycle of the saved object, and the policy that determines the "key" equivalence are different.

Execution efficiency is a big problem in map. Look at what get () does, and you'll see why searching for "keys" in ArrayList is pretty slow. And that's where the hashmap to improve speed. HashMap uses a special value, called a hash code, to replace the slow search for keys. A hash code is a "relatively unique" int value that represents an object that is generated by converting some information of that object. All Java objects can produce hash codes, because Hashcode () is the method defined in the base class object.

HashMap is a quick query using the object's Hashcode (). This method can significantly improve performance.

MAP: Maintain the relevance of key-value pairs so that you can find "values" by "Keys"

Hashmap:map based on the implementation of the hash table. The cost of inserting and querying "key-value pairs" is fixed. The capacity capacity and load factor load factor can be set through the constructor to adjust the performance of the container.

Linkedhashmap: Similar to HashMap, but when iterating through it, the order in which key-value pairs are obtained is their insertion order, or the least recently used (LRU) order. Just a little slower than HashMap. The iteration is accessed faster because it uses the list to maintain the internal order.

TREEMAP: Based on the implementation of red-black tree data structure. When you look at key or key-value pairs, they are sorted (the order is determined by comparabel or comparator). TreeMap is characterized by the fact that the results you get are sorted. TreeMap is the only map with the Submap () method, which can return a subtree.

Weakhashmao: The objects used in the weak key (weak key) Map,map are also allowed to be released: This is designed to solve special problems. If no references outside of map point to a key, the key can be reclaimed by the garbage collector.

Identifyhashmap:: Use = = instead of equals () to compare the "key" to the hash map. Designed to solve special problems.

1.4 Differences between 1.4.1, Collection, and Map

The number of elements stored in the container is different.
collection type, with only one element per position.
Map type, holding Key-value pair, like a small database.

1.4.2 and their respective sub-category relations

Collection
--list: Elements are stored in a specific order. So the order taken out may be different from the order in which it is put.
--arraylist/linkedlist/vector
--set: cannot contain duplicate elements
--hashset/treeset
Map
--hashmap
--hashtable
--treemap

1.4.3, other characteristics

List,set,map holds objects as object types.

Collection, List, Set, and map are interfaces and cannot be instantiated.
ArrayList, vectors, HashTable, and HashMap are inherited from them, and these can be instantiated.
The vector container knows exactly what type of object it holds. Vectors do not perform boundary checks.

Summary 1. If it involves operations such as stacks, queues, and so on, you should consider using the list, for quick insertions, for deleting elements, should use LinkedList, and if you need to quickly randomly access elements, you should use ArrayList.
2. If the program is in a single-threaded environment, or if access is done only in one thread, it is more efficient to consider non-synchronous classes, and if multiple threads may operate on a class at the same time, the synchronized classes should be used.
3. Use Hashset,hashmap in addition to treeset,treemap when sorting is required, as they are more efficient.
4. Pay special attention to the operation of the hash table, and the object as key should correctly replicate the Equals and Hashcode methods.

5. The container class can only hold object references (pointers to objects), rather than copy the object information to a position in a sequence. Once the object is placed inside the container, the object's type information is lost.
6. Try to return the interface instead of the actual type, such as returning list instead of ArrayList, so that if you need to change ArrayList to LinkedList later, the client-side code does not have to be changed. This is for abstract programming.

Note: 1, collection does not have a get () method to get an element. Elements can only be traversed by iterator (). 2. Set and collection have identical interfaces. 3, List, you can use the Get () method to remove one element at a time. Use numbers to select one of a bunch of objects, get (0) .... (Add/get) 4, the general use of ArrayList. Use LinkedList to construct stack stacks, queue queues.      5, map with put (K,V)/get (k), you can also use ContainsKey ()/containsvalue () to check if it contains a key/value. HashMap will use the object's hashcode to quickly find the key. 6, the element in the map, you can extract the key sequence, the value sequence alone. Use Keyset () to extract the key sequence and generate a set for all keys in the map. Use values () to extract the value sequence and generate a collection for all values in the map. Why a build set, a Build collection?  That's because key is always unique, and value allows repetition. Original address: 22398395

Collection & array 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.