Preface: In Java Development we can not leave the collection array, and in Java there is a proper noun: "container", the following will be combined with thinking in Java knowledge and the actual development of business scenarios to tell the container in the Web project usage. You can learn about containers in Java with picture code
Note: This place, referring to the blog in the direction of the far-away Java container, since the predecessors summed up so well, I will directly use, here more attention in the actual development of the examples, thanks to those who summed up the predecessors, hard.
A simple Array example
Thinking in Java does not classify arrays as Java containers, actually arrays are not Java-exclusive C + +, C has arrays. However, when it comes to web development, I still classify the arrays into containers because they're doing the same thing.
Another point of detail is that I've been through the projects I've developed, but I'm surprised to find that it's very rare for so many projects to store objects directly in arrays. Think of the same, Java is Object-oriented, and the array to Java is always a bit lower.
Cherish This hard-won demo:
Public map<string, String> Getdimvalue () { if (this.dimvalue! = null) return dimvalue; This.dimvalue = new hashmap<string, string> (); if (This.dim! = null && this.dim.length ()! = 0) { string[] strdims = This.dim.split (",");//Can be intercepted by the way, get string[ ] for (String s:strdims) { string[] dims = s.split ("\ \:"); This.dimValue.put (Dims[0], dims[1]);//array access through subscript, but note up to array[array.length-1], out-of-bounds directly throws an exception, unlike C + + } return this.dimvalue; }
Arrays (array) are the most common data structures. An array is an ordered collection of elements of the same type and has a fixed size (which can hold a fixed number of elements). An array can randomly access (random access) elements according to the subscript (index). In memory, an array is usually a contiguous unit of storage.
Java supports arrays of this data structure. We need to explain the type and size of each array,Java using byte[] can represent BLOB fields, store pictures, Xml,json, etc. String[] can be used to save some strings, IDs, code, and so on.
Common byte[in Web projects] to store BLOB fields, etc.
@Type (Type = "Org.springframework.orm.hibernate3.support.BlobByteArrayType") private byte[] globals;
In the description type, add a [] after the type description (String) to indicate that it is an array. When you create a container using new, you need to describe the size of the array, or direct int a = {n/a} to initialize it directly with {}.
Arrays can be traversed to other container types, but other types can be quickly converted to arrays via ToArray () (Arrays, the tool class can convert an array to a list)
First Branch: Collection
In development, collection is most commonly used in two classes: Set and list. Because it belongs to one collection, it is convenient to convert each other, and the method of invocation is similar. (Collection Api)
Common method Interfaces in Java:
* Boolean Add (Object obj): Add objects, change the collection to return true* Iterator Iterator (): Object that returns the Iterator interface * int size () * Boolean IsEmpty () * Boolean contains (Object obj) * void Clear () * <T> t[] ToArray (t[] a)
The above interface is referenced in: Wishyouhappy's blog: Java container summary.
1:list Collection
You can view the list of Chinese documents, the document is clearly described to list<e> is a implementation of the collection interface, and we can directly use the list to declare the object (the interface can directly declare an object). the container's reference is a list type, but the container's implementation is the ArrayList class. Here is the separation of the interface from the implementation class. In fact, the same abstract data structure (ADT) can have a number of implementations (such as stacks and lists) that can be implemented by the stack. This separation allows us to choose the implementation of ADT more freely (refer to the Java container for details)
The more commonly used arraylist,linkedlist in Java, the elements in the collection can be equal, in order
1 public class Test {2 public static void main (string[] args) {3 list<string> List = new ArrayList <String>(); 4 //Add a single element 5 for (String s1: "Hehe wo shi Lao da". Split (" } 8//Add multiple Elements 9 list.) AddAll (Arrays.aslist ("Nan dao ni bu xin?"). Split ("" System.out.println (List.tostring ());//list overrides the ToString method, outputting each element in the list 11//Modify the element of position I to (int i = 0; I<list.size (); i++) {List.set (I, "U" System.out.println (List.tostring ()); List.removeall ( Arrays.aslist (New string[]{"U" }20}
The above code just to illustrate the main purpose of the list, in fact, the development may not use so much, the more commonly used also
- Add () method to add a new element
- The Get () method can get the elements in the container, passing an integer subscript as a parameter
- The Remove () method removes the element from the container and passes an integer subscript as a parameter. (There is another remove (), passing the element itself as an argument)
- The size () method is used to return the total number of elements in the container.
- ToString () More for debugging code Yes, view contents in list
- AddAll () Add a list of the same type
List also has an internship class linkedlist more commonly used, it can be used to do the queue implementation, can also be disguised to complete the work of the stack.
The main methods are:
- Get (int index): Returns the element at the specified position in this list.
- GetFirst (): Returns the first element of this list.
- GetLast (): Returns the last element of this list.
- IndexOf (Object O): Returns the index of the specified element that first appears in this list, or 1 if the element is not included in this list.
- LastIndexOf (Object O): Returns the index of the last occurrence of the specified element in this list, or 1 if the element is not included in this list.
- Remove (): Gets and removes the header of this list (first element)
- Removefirst (): Removes and returns the first element of this list
- Removelast (): Removes and returns the last element of this list
The listedlist uses chained storage. Chained storage will set a node. Includes three-part precursor nodes, successor nodes, and data values. So when storage is stored, his physical address is not necessarily contiguous.
Specific content can refer to the Java Increase (22)---LinkedList The following is a list of the linkedlist part of the source code (not recommended to start)
View Code2:set Collection
A collection (set) is also a collection of elements. No equivalent elements are allowed in the collection, and the elements of the collection are not in order:
We use set most of the time to take advantage of its characteristics, and there are no duplicate elements, such as:
2.1 Hashset:hashset query speed is faster, but the stored elements are random and not sorted
public class test{public static void main (string[] args) { set<integer> s1 = new hashset< Integer>(); S1.add (4); S1.add (5); S1.add (4); S1.remove (5); System.out.println (S1); System.out.println (S1.size ()); }}
We can use it to filter the duplicate data, the Set can be easily converted to list, because the constructor method passed in the parameter is collection< Extends e> C
1 set<string> Set = new hashset<string>(), 2 set.add ("H"), 3 Set.add ("H"), 4 list<string> Fromsets = new Arraylist<string> (set), 5 System.out. println (Fromsets.tostring ()); 6 set<string> S1 = new hashset<string>(fromsets); 7 System.out.println (S1.tostring ());
This place, very interesting is that hashset in the possession of HashMap, using HashMap access to data
Public HashSet (collection<? extends e> c) { map = new Hashmap<e,object> (Math.max ((int) (C.size ()/. 75f) + 1, +)); AddAll (c); }
HashSet only the Add method, there is no get method (this is slightly different from the list). But HashSet implements the iterator<e> iterator(). Can be traversed by iterator, can see the set Chinese document
2.2:treeset
TreeSet is to store elements in a red-black tree structure, so the stored results are ordered
public static void main (string[] args) { random random=new random (n); Set<integer> intset=new treeset<integer>(); for (int i=0;i<10000;i++) { intset.add (random.nextint); } System.out.print (Intset); }
The iterator in 3:collection
Iterator's official documentation,The general set wants to take the element only through the iterator, and the list can also use an iterator (usually with get)
public class test{public static void main (string[] args) { list<integer> l1 = new Arraylist<integer>(); L1.add (4); L1.add (5); L1.add (2); Iterator i = l1.iterator (); while(I.hasnext ()) {System.out.println (I.next ()); }}}
Collection can be used with foreach because it implements the iterator interface
public class Iteratorclass {public iterator<string> Iterator () { return new Itr (); Private class Itr implements iterator<string>{ protected string[] words= ("Hello Java"). Split (""); c10/>private int index=0; public boolean Hasnext () {return index<words.length;} public String NEX T () {return words[index++]; public void Remove () {}}} /c2>
The Foreach loop will eventually be converted to Iterator traversal (Iterator it=iterator;iterators.hasnext ();)
Iterator iterators=new Iteratorclass (). Iterator (); For (Iterator it=iterator;iterators.hasnext ();) { System.out.println (Iterators.next ()); } while (Iterators.hasnext ()) { System.out.println (Iterators.next ()); }
Let's talk about some of the most error-prone points in Java:
For Loop finds an element in the collection and deletes it: very easy to appear java.util.ConcurrentModificationException
list<string> list = new arraylist<string>(), List.addall (Arrays.aslist ("Nan dao ni bu xin?"). Split (""))); for(String st:list) { System.out.println (ST); if (St.equals ("ni")) { list.remove (ST); }}
The solution is to convert the array to iterator and then take advantage of It.remove (); Delete the elements in the array
public static void main (string[] args) { list<string> list=new arraylist<string>(); List.add ("a"); List.add ("BB"); List.add ("A22"); Iterator<string> it=list.iterator ();//remove element of "a" in arraywhile (It.hasnext ()) {String st=it.next (); if (St.equals ("a")) {It.remove ();}} }
A second branch: MAP
In Web projects, map is very common, and of course, in many cases, maps are replaced by some wrapper classes (which is actually referred to in agile development using VO to replace the map). But the map is still unstoppable container of a brother.
Common method Interfaces in Java
* Object get (Object key) * object put (object key, Object value) * Set KeySet (): Returns the keys set set< K> KeySet () * Set EntrySet (): Returns mappings Set set<map.entry<k,v>> entryset () * ContainsKey () * Containsvalue ()
Map is a collection of key-value pairs. Each element in the map is a key-value pair, which is a key (key) and its corresponding object value (value). For the map container, we can find the corresponding object by the key.
Hash table is a common way of implementation of map, but also the most widely used in the actual development (HASHMAP), want to understand the principle of HashMap, can refer to HASHMAP realization principle analysis
public class test{public static void main (string[] args) { map<string, integer> m1 = new HASHM Ap<string, integer>(); M1.put ("Vamei",); M1.put ("Jerry", 5); M1.put ("Tom",); System.out.println (M1.get ("Vamei"));}}
In map, we use the put () method to add elements and get the elements using the Get () method.
The map also provides the following method to return a collection:
- KeySet () converts all keys to set
- VALUES () converts all values to a list
- ContainsKey Verify that there is a primary presence, Containsvalue Verify that the value exists
- EntrySet gets the key-value pair.
Summarize:
There are some tool classes in Java to help us deal with container-related content. For example, some of the classes in Arrays,java are useful to these tool classes
Clone method in source code of ArrayList
/** * Returns A shallow copy of this <tt>ArrayList</tt> instance. (The * elements themselves is not copied.) * * @return A clone of this <tt>ArrayList</tt> instance * /Public Object clone () { try< c10> { arraylist<e> v = (arraylist<e>) Super. Clone (); V.elementdata = arrays.copyof (elementdata, size); V.modcount = 0; return v;} catch (Clonenotsupportedexception e) {//This shouldn ' t happen, since we is cloneable throw New Internalerror (); } }
The ToArray () method in ArrayList source code
Public object[] ToArray () { return arrays.copyof (elementdata, size); }
If you are interested in arrays this tool class, you can take a look at the source code, it finally calls to the local method (folded up, do not want to confuse the reader)
View Code
Some other ways to arrays:
- Sort (): Sorts incoming collections (specific algorithms can refer to Java arrays.sort Source code parsing)
- Aslist (): Convert Array to List
- BinarySearch (): Two-point lookup array
- Deeptostring (): Convert two-dimensional array to string
- Fill (): Quick Fill Array
Another example is collections:
can refer to the use of the thinking in Java Collections Tool class
View Code
Max (): Fetch the largest element of the collection
Sublist (): Intercept list
AddAll (): Add collection
Interested can go to see the source code, I think very helpful
Application of Java container in real project