If a project just uses an array to manipulate a known number of objects and knows the life cycle of each object , then this will be a very simple program. Facing the current huge and complex business logic, it is far from enough to hold objects in an array, so Java provides a container class library to meet the requirements of managing the number of variable objects .
1. Java Container Class Library
- Purpose - to save the object
- The Arrays.asList() method accepts an array or a comma-separated list of elements (and accepts a variable parameter) and converts it to a List object;
- The Collections.addAll() method accepts a Collection object, and an array or a comma-separated list (and accepts a variable parameter) to add elements to the Collection;
- Collection itself has a constructor that can receive another Collection to initialize itself;
- Collection.addAll() can only receive another Collection, so it is not as flexible as Collections.addAll(), so the latter is preferred.
See an example:
import java.util. *; public class Box{ //Create a method to receive Collection public static Collection setCollection(Collection con){ con.add("one"); con.add("two"); con.add("three"); con.add("three"); con.add("two"); return con; } //return a method that receives a Map public static Map setMap(Map map){ map.put("one","one"); map.put("two","two"); map.put("three","three"); map.put("three","three"); return map; } public static void main(String[] args){ System.out.println(setCollection(new ArrayList<String>())); System.out.println(setCollection(new LinkedList<String>())); System.out.println(setCollection(new HashSet<String>())); System.out.println(setCollection(new TreeSet<String>())); System.out.println(setCollection(new LinkedHashSet<String>())); System.out.println(setMap(new HashMap<String,String>())); System.out.println(setMap(new TreeMap<String,String>())); System.out.println(setMap(new LinkedHashMap<String,String>())); } }
Compile and execute:
Analyzing this example we draw the following conclusions:
- ArrayList, LinkedList, HashSet, TreeSet, LinkedHashSet can all be upcast to Collection, that is, Collection is the public interface of these collections.
- Map is the public interface of HashMap (with the fastest search technology), TreeMap, and LinkedHashMap.
- List collections include ArrayList and LinkedList collections, both of which can store duplicate objects.
- The Set collection includes HashSet ( using a hash function , the fastest way to get elements), TreeSet, LinkedHashSet, which store different objects.
- TreeSet ( stores elements in a red-black tree data structure ) saves objects in ascending order of comparison results.
- LinkedHashSet ( which also uses hashing, and uses a linked list to maintain the insertion order of elements ) holds objects in the order in which they were added.
- TreeMap stores keys in ascending order of comparison results.
- LinkedHashSet holds keys in the order in which they were added.
- Observe the running results and find that there are two notes , which means that we use a thread-unsafe collection (detailed later), but it will not affect the running of the program.
2. List collection
Elements can be maintained in a specific sequence ( a mutable sequence ). It adds a large number of methods on the basis of Collection, so that it can insert and remove elements in the middle of List.
Specifically, two kinds of Lists are implemented:
- ArrayList - Good at random access to data, slow to insert and remove elements in the middle.
- LinkedList - inserting and removing elements in the middle is better than the former, good at sequential access, slow random access
*Several common methods:
- contains() is a method in the interface Collection, which is used to determine whether a collection contains an object and returns a value of type boolean, so this method is available in both implementation classes of List.
- remove(reference) - removes the specified referenced object from the collection.
- indexOf(reference) - Gets the index value corresponding to the specified reference in the collection.
- subList(startIndex,endIndex) - can create a segment from a large list (the segment between the start index and the end index, including startIndex and endIndex).
- containAll() - Whether a set contains another set (also can be said to be a fragment), the order of the elements in the set will not affect the judgment result.
- retain() - Find the intersection of two sets (internal dependencies and equals when judging).
- removeAll() - removes all elements of the parameter set from this set (depending on equals).
- set() - can replace the element at the specified index.
- addAll()——List rewrites the Collection method, which can insert the specified fragment under the specified index. Of course, you can also append another fragment directly after the collection.
- clear() - clears all elements in the collection
- isEmpty() - Returns a boolean value to determine whether the collection is empty.
- toArray() - can convert a collection into an array, pass a collection of the specified type, and an array of the specified type will be generated.
*LinkedList collection:
It contains methods to make it work as a stack, queue, or deque .
getFirst()\element() - Both methods are exactly the same, both return the first element of the list without removing it, and throw a NoSuchElement-Exception if the List is empty.
peek() - both return the first element of the list, do not remove it, return null if the list is empty.
removeFirst()\remove() - Both methods are the same, they remove and return the head of the list, and throw a NoSuchElementException if the list is empty.
poll() - slightly different from the above two, but returns null when the list is empty.
removeLast() - removes and returns the last element in the list.
addFirst()\add()\addLast() - they all insert the element at the end (end) of the list.
- stack:
A container called last-in-first-out (LIFO), also known as an overlay stack. LinkedList has methods that can directly implement all functions of the stack, so LinkedList can be used directly as a stack.
public class Stack<T>{ private LinkedList<T> stack=new LinkedList<T>(); public void push(T t){ stack.addFirst(t); } public T peek(){ return stack.getFirst(); } public T pop(){ return stack.removeFirst(); } public boolean empty(){ return stack.isEmpty(); } public String toString(){ return stack.toString(); } }Although the Stack class is created in Java's util class library, the use of the above-mentioned stack created by LinkedList is more advocated in actual development. It should be noted that when creating a Stack class, it is best to call only the methods required by the stack instead of the entire stack. LinkedList (which has a bunch of other methods) is inherited.
3. Set collection
Do not save duplicate elements, because it is easy to ask whether an object is in a certain Set, so lookup is a very important operation of Set collection, HashSet is optimized for fast lookup . Set and Collection have exactly the same interface, without any additional functionality , but with different behaviors (this is a typical application of inheritance and polymorphism - showing different behaviors).
import java.util. *; public class Box{ public static void main(String[] args){ Set<String> t_box=new TreeSet<String>(); //Add data to the Set collection Collections.addAll(t_box,"B,A,C,E,D,F".split(",")); Set<String> h_box=new HashSet<String>(); Collections.addAll(h_box,"E,D,F".split(",")); System.out.println(t_box); System.out.println(h_box); System.out.println("contains:"+t_box.contains("A")); System.out.println("containsAll:"+t_box.containsAll(h_box)); h_box.removeAll(t_box); System.out.println(h_box); System.out.println(t_box); System.out.println("isEmpty:"+h_box.isEmpty()); } }
operation result:
Use the contains() and containsAll() methods to test the ownership of a Set.
To be continued. . . . . .