Java container Basics
Java container Basics
The Java utility Library provides a Set of well-developed container classes. The basic types are List, Set, Map, and Queue. They all have some features. For example, Set stores only one object for each value. Map allows you to associate objects with objects. In addition, the Java container class can automatically adjust the size. Therefore, unlike arrays, you can place any number of objects in the container without worrying about how large the container should be.
The Java container class has four interfaces: List, Set, Map, and Queue. Ideally, most of the code you write is dealing with these interfaces, in addition, the only place you need to specify the exact type to be used is when creating the instance. For example, you can create a list:
List list = new ArrayList ();
The purpose of using the interface here is to modify your implementation only in the created place when you need to modify it. Therefore, you can modify it as follows:
List list = new vertex List ();
Therefore, you should create a specific class object, convert it to the corresponding interface, and then use this interface in other code. However, this method does not always work because some classes have additional functions. For example, the listlist interface has additional methods not included in the List interface. Therefore, if you need to use these methods, you cannot convert them into more common interfaces.
Here, we will focus on the basic knowledge and typical usage of the Java container class.
1. Basic Concepts
The Java container class library is used to save objects and divide them into two different concepts:
1) Collection: a sequence of independent elements. List elements must be saved in the inserted order. set elements cannot have duplicate elements. queue determines the order of elements according to queuing rules.
2) Map: a key-Value Pair object that forms a pair. You can use the key to find the value. ArrayList allows you to use numbers to search for values. In a sense, ArrayList associates numbers with objects. Map allows us to use one object to find another object, also known as an associated array. We should associate some objects with other objects.
import java.util.*;public class PrintingContainers{static Collection fill(Collection
collection){collection.add("rat");collection.add("cat");collection.add("dog");collection.add("dog");return collection;}static Map fill(Map
map){map.put("rat","123");map.put("cat","456");map.put("dog","789");map.put("dog","268");return map;}public static void main(String[] args){System.out.println(fill(new ArrayList
()));System.out.println(fill(new LinkedList
()));System.out.println(fill(new HashSet
()));System.out.println(fill(new TreeSet
()));System.out.println(fill(new LinkedHashSet
()));System.out.println(fill(new HashMap
()));System.out.println(fill(new TreeMap
()));System.out.println(fill(new LinkedHashMap
()));}}/*output:[rat, cat, dog, dog][rat, cat, dog, dog][cat, dog, rat][cat, dog, rat][rat, cat, dog]{cat=456, dog=268, rat=123}{cat=456, dog=268, rat=123}{rat=123, cat=456, dog=268}*/
The difference between the two main types in the Java container class library is that the number of elements saved in each "slot" in the container. You can view the output and find that the default printing behavior (using the toString method provided by the container) can generate good readability results. The printed content of the Collection is enclosed in square brackets. Each element is separated by a comma. Map is enclosed in braces, and the key and value are associated with the equal sign. These containers are only used for demonstration. They will be described in more detail later.
2. Introduction to Common Containers
1) Collection
The following table lists all the methods that can be executed through Collection. They are also operations that can be performed by Set and List.
2) List
The List interface adds a large number of methods on the basis of Collection, so that you can insert and remove elements in the middle of the List.
There are two types of List:
· Basic ArrayList, which is good at random element access, but it is slow to insert and delete elements in the List (underlying implementation: array ).
· Shortlist, which performs insert and delete operations in the List at a low cost, provides optimized sequential access, but is relatively slow in Random Access (underlying implementation: bidirectional linked List ).
The following lists some common methods in List:
Contains (): used to determine whether an object is in the list
Remove (): used to remove objects from the list.
IndexOf (): used to determine the index number of an object in the list.
SubList (): used to create a list clip.
RetainAll (): used for "intersection" operations
Set (): used to set the object at the specified index
3) Upload list
Consumer List implements the basic List interface, and also adds methods to make it stack, queue, and double-end queue.
Some of these methods only have some differences in names, or only some differences, so that these names are more suitable in a specific context. For example:
GetFirst () and element () are exactly the same. They both return the first element of the list without removing it. remove () and removeFirst () are also the same, they remove and return the header of the List; add () and addLast () are both the same, they all Insert elements into the end of the list;
4) Set
Set does not save repeated elements. The most common method of Set is to test the property normalization. You can easily ask whether an object is in a Set. Set has the same interface as Collection, so there is no additional function, unlike the previous two different lists. Set is actually a Collection, but the behavior is different (this is a typical application of inheritance and polymorphism );
import java.util.*;public class SetOfOperations{public static void main(String[] args){Set
set1=new HashSet
();Collections.addAll(set1,"A B C D E F G H I J K L".split(" "));set1.add("M");System.out.println("H: "+set1.contains("H"));System.out.println("N: "+set1.contains("N"));Set
set2=new HashSet
();Collections.addAll(set2,"H I J K L".split(" "));System.out.println("set2 in set1: "+set1.containsAll(set2));set1.remove("H");System.out.println(set1);System.out.println("set2 in set1: "+set1.containsAll(set2));set1.removeAll(set2);System.out.println("set2 remove from set1: "+set1);Collections.addAll(set1,"X Y Z".split(" "));System.out.println("'X Y Z' add to set1: "+set1);}}/*output:H: trueN: falseset2 in set1: true[D, E, F, G, A, B, C, L, M, I, J, K]set2 in set1: falseset2 remove from set1: [D, E, F, G, A, B, C, M]'X Y Z' add to set1: [D, E, F, G, A, B, C, M, Y, X, Z]*/
5) Map
The ability to map objects to other objects is an easy way to solve programming problems;
For example:
import java.util.*;public class Statistics{public static void main(String[] args){Random rand=new Random(47);Map
m=new HashMap
();for(int i=0;i<10000;i++){int r=rand.nextInt(20);Integer feq=m.get(r);m.put(r,feq==null?1:feq+1);}System.out.println(m);}}/*output:{0=481, 1=502, 2=489, 3=508, 4=481, 5=503, 6=519, 7=471, 8=468, 9=549, 10=513, 11=531, 12=521, 13=506, 14=477, 15=497, 17=509, 16=533, 19=464, 18=478}*/
6) Queue
A queue is a typical first-in-first-out container, that is, putting a thing at one end of the container and taking it from the other end. The order of putting a thing into the container is the same as that of taking it out. Queues are often used as a reliable way to transmit objects from a certain area of the program to another area, which is particularly important in concurrent programming.
The Queue list provides methods to support Queue behavior and implement the Queue interface. Therefore, the Queue list can be used as an implementation of Queue.
import java.util.*;public class QueueDemo{public static void printQueue(Queue queue){while(queue.peek()!=null){System.out.print(queue.remove()+" ");}System.out.println();}public static void main(String[] args){Queue
queue=new LinkedList
();Random rand=new Random(47);for(int i=0;i<10;i++)queue.offer(rand.nextInt(i+10));printQueue(queue);Queue
qc=new LinkedList
();for(char c:"HelloWorldJava".toCharArray())qc.offer(c);printQueue(qc);}}
Some common Queue methods are listed below:
Offer (): insert an element to the end of the team
Peek ()/element (): returns an object without deleting it.
Poll ()/remove (): remove and return the opposite
3. iterator
An iterator is an object that traverses the objects in the selected container. They only use containers and do not know or care about the container type to reuse code. In addition, the iterator is also called a lightweight object: it has a low cost to create it;
Iterator usage:
1) Using iterator () requires the container to return an Iterator ();
2) use next () to obtain the next element in the container;
3) Use hasNext () to check whether there are any elements in the container;
4) use remove () to delete the elements returned by the iterator;
Summary
Java container diagram. Common Containers are represented by black rough wireframes, vertex wireframes represent interfaces, and solid wireframes represent specific classes. A dot line with hollow arrows represents a specific class to implement interfaces, A solid arrow indicates that a class can generate the object pointed to by the arrow;
Below are some small suggestions for container selection:
1) If you want to perform a large number of random access, use ArrayList. If you need to insert or delete elements from the middle of the table, use the sort list;
2) HashMap is designed for fast access, while TreeMap keeps keys in the sorting state, so there is no HashMap fast. LinkedHashMap maintains the insertion sequence of elements, but it also provides fast access through hash.
3) TreeSet does not accept repeated elements. HashSet provides the fastest query speed, while the TreeSet keeps the elements in order, and the sorted HashSet stores the elements in insert order.
4) The program should not use outdated vectors, stacks, and HashTable;