One 、ArrayList Use ( A little )

Two 、 Basic concept of container

( One )、Collection Is the basic interface of a collection class

The main method :

public interface Collection<E>{
boolean add(E element);// Add elements to the collection ,E For generics
Iterator<E> iterator();// Back to implementation Iterator Object of the interface

About :Iterator After that, I will explain .

( Two )、 Realized Collection Subclasses of :

List: Insert save elements in order .                  Set: There can't be duplicate elements in this container                     Queue: Determine the order of objects according to the rules of the queue

( 3、 ... and )、Map Interface

Definition : One makes right “ Key value pair ” object , Use key lookup value

notes :Map This is a separate interface , Do not belong to Collection, So map None of the ending classes belong to Collection

( Four )、 Use the container according to the appeal analysis

1、ArrayList Go up to Collection, And pass Collection Add processing data .( Technology applied : The parent class reference points to the subclass object , Call the method of the subclass )

public class UpToCollection {
public static void main(String [] args){
ArrayList<Integer> arrayList = new ArrayList();
for(int i=0; i<5; ++i){
Collection<Integer> collection = arrayList;
// It's used here foreach loop , As long as it's done Iterator Interface can be used foreach
//Collection No, List Of get Method , Need to use Iterator Let's do the traversal
for(Integer i: collection){

2、 Add a set of elements

public class AddElementToCollection {
public static void main(String[]args){ Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6));
// Knowledge point 1: utilize Arrays This static class , Will array , Or a column of numbers converted to List
// Knowledge point 2:ArrayList Can be nested List establish
/* Knowledge point 3: Why not? Collection<Integer> collection =
* Arrays.asList(1,2,3,4,5,6);, Found no problem creating , But when it comes to the following
* collection.addAll(Arrays.asList(datas)); It's a mistake
* reason : because Arrays.asList(1,2,3,4,5,6) Created List It's a fixed length List
* So it's impossible to execute add() Methodical .
Integer [] datas = {7,8,9,10};
/* Knowledge point 4: You have to use Integer As a class , Out of commission int, Otherwise, an error will be reported
* Because before Collection<Integer> collection, Generics have been defined as Integer
* So you can't use reference types , Get what the input generics are , You need to create an array of classes
for(Integer i: collection){
// Above is the passage of Collection Go to List Add a set of data to ( Array , Or custom data ), Here's another way Collections.addAll(collection, 11,12,13,14,15,16);
Collections.addAll(collection, datas);
// notes : This is a Collections The class is not Collection class


Collection How to add elements   advantage : The method is efficient .   shortcoming : But you need to create a Collection class , As an object

Collections How to add elements advantage : convenient , No need to create Collection class .

3、Collection Role of type : Unified type add , Delete ...( Uniform traversal is made up of Iterator affirmatory )

public class CollectionEffect {
// Unify all kinds of containers , Just one way to add , Delete
public static void main(String[] args){
print(fill(new ArrayList<String>()));
print(fill(new HashSet<String>()));
print(fill(new HashMap<String,String>()));
//Collection Collection of interfaces
public static Collection<String> fill(Collection<String> c){
return c;
// heavy load fill Method , Provide Map Interface
public static Map<String,String> fill(Map<String,String> map){
map.put("dog", "pig");
map.put("cat","small"); return map;
} public static void print(Collection<String> c){ } public static void print(Map<String,String> map){ }


3、 ... and 、 iterator (Iterator)

effect : Uniform traversal of various containers

Interface method :

public interface Iterator<E>{
E next();// Get next element
boolean hasNext();// See if the next element exists
void remove();// Remove elements


Be careful :1. In the use of next() Method before using hasNext(); and remove() They exist in pairs .

Use :

public class UseIterator {
public static void main(String[]args){
ArrayList<Integer> arrayList = new ArrayList();
for(int i=0; i<5; ++i){
// obtain Iterator, The method is from Collection Interface inherited from
Iterator<Integer> iterator = arrayList.iterator();
// Use
Integer x =;


Uniform traversal : modify Medium print Method ,

//... Continued above 
public static void print(Iterator<String> iterator){


Four 、 A specific collection

①、ArrayList: Arrays that can grow and shrink dynamically , Easy to search , Not conducive to insertion and deletion .   Detailed explanation : A little .

②、LinkedList: A sequence of linked lists , Easy to insert , And delete , It's not good for finding .LinkedList It also provides a way to use it as stack and queue or double ended queue . Lead to LinkedList Of Iterator Unlike other collections , So we'll introduce it later .

Give Way LinkedList Realization Stack( Already there. Stack This class , however LinkedList Can produce better Stack)

public class LinkedListStack<T> {
private LinkedList<T> mLinkedList;
public LinkedListStack(){
mLinkedList = new LinkedList<T>();
// Push
public void push(T view){
// Get stack top element
public T peek(){
return mLinkedList.getFirst();
// Remove the top element
public T pop(){
return mLinkedList.removeFirst();
} public boolean isEmpty(){
return mLinkedList.isEmpty();
public String toString(){
return mLinkedList.toString();


Others are not available for the time being .

LinkedList The iterator ListIterator

1、 It can only be used for a variety of List Class method .

2、 effect :Iterator Can only move forward ,ListIterator It can move in two directions .

public class UseListIterator {
public static void main(String[] args){
LinkedList<Integer> linkedList = new LinkedList<Integer>();
for(int i=0; i<10; ++i){
// obtain ListIterator
ListIterator<Integer> listIterator = linkedList.listIterator();
//linkedList.listIterator(3); Give Way Iterator Start at the third position
int i =;
// New characteristics 1: The ability to modify data at the current location
// characteristic 2: Be able to move forward , And get the data


③、Set: Don't save duplicate elements .

Hash set (Hasing): Reading data is not in the order in which it was stored ( Stochastic ranking ), Can quickly find the required objects .

principle : The hash table calculates an integer for each object , Called hash code . Hash codes are integers generated by object instance fields ( No matter the algorithm )、

notes : If it's a custom class , Is responsible for the implementation of this class hashCode, Self realized hashCode The method should be the same as equals Method compatible ( That is, if there is a return true Then all should return to true)

stay JAVA Hash table is realized by linked list array ( There's an array , Each array holds a linked list ), Each position in this array is called “ bucket ”.

The role of the barrel : Solve the problem of the same hash code 、 When the hash code is the same, put the data into the bucket's linked list . After querying the bucket, traverse the linked list of the bucket .

Little knowledge : When you insert too much data , It may lead to the barrel being full , So when the bucket is occupied more than 75% When , It's going to rehash ( Create a new table to increase the number of buckets , Move the data from the old table to the new table ).

Tree set (Tree): Is an ordered set , You can insert elements into a collection in any order , But when I take it out , Each value is automatically implemented in the sorted order .( Add each element to the tree , They're all in the right place )

ask :Tree How to know how you want each element to be arranged ?

rewrite Comparator Interface , And passed in to TreeSet<E> in .

public class UseTreeSet {
public static void main(String[]args){
// by TreeSet Add logic for comparison
Comparator<Integer> compatator = new Comparator(){ @Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
// Here's the logic
return 0;
} };
TreeSet<Integer> treeSet = new TreeSet(compatator);


So : To use TreeSet The step is ①、 Create a class and override equal() and hashCode()②、 establish Comparator Interface , And rewrite coparator() Method ③、 take Comparator Object to TreeSet in

queue (Queen):ArrayDeque and LinkedList Realization . And both classes implement two terminal queues ( It can be added and deleted at the beginning and end of the linked list ),LinkedList Realized Queue Interface ArrayDeque Realized Deque Interface . There's also a special queue “ Priority queue (Priority queue)”, Insert any , Read in priority order .( Priority is related to Tree equally , By rewriting Coparator Interface to sort , If you don't rewrite it Coparator Then we sort them naturally —— Call object equal() Method ).

The mapping table (Map): Through the key you set (key) Find the corresponding value (value). because Map Do not belong to Collection that , How to traverse Map Of key, or Map Of value, also key And value At the same time through

1、 Traversing key information

HashMap<String,String> map = new HashMap();
map.put("asd", "zxcdd");
// Traverse Map All the keys in
Set<String> set = map.keySet();// By acquiring Set Map all the keys in the table
// notes : The Set No HashSet Neither TreeSet, It just works Set The class of the interface
for (String str : set){

Traversing key information

2、 Traverse the information of the value

// Connect 
// Traverse all values
Collection<String> collection = map.values();// obtain Collection Get value
for (String str : collection){

Traversal value

3、 All over

 // All over 
for (Map.Entry<String,String> mapData : map.entrySet()){
String key = mapData.getKey();
String value = mapData.getValue();

5、 ... and 、 Customize Collection and Iterator

1、 By inheritance Collection Interface implementation method   shortcoming :Collection There are too many methods to override , It takes a lot of energy

2、 therefore JAVA Provides AbstactCollection Method , Completed most of Collection Method   shortcoming : When a class has inherited other classes , Must be rewritten Collection.

3、 Rewrite directly Iterator Interface .

Thinking in Java—— aggregate (Collection) More articles about

  1. java aggregate ——Collection Interface

    Collection yes Set,List Interface's parent class interface , Data used to store collection types . 2. Method int size(): Returns the length of the set void clear(): Remove all elements from the collection , Change the set length to 0 Ite ...

  2. Java aggregate Collection And List Detailed explanation of

    1. What is a collection The container where the object is stored , Object oriented language embodies things in the form of objects , So in order to facilitate the operation of multiple objects , Store the object , Collections are the most common way to store objects . Collections are created to hold objects . Collection can store any type of ...

  3. Java aggregate -Collection Interface and iterator implementation

    2017-10-30 00:30:48 Collection Interface Collection hierarchy Root interface in .Collection Represents a set of objects , These objects are also called collection The elements of . some c ...

  4. Java aggregate Collection The basic method

    jdk1.7 api Method summary in : Reference resources java Set up the whole picture : Collection by List.Se ...

  5. JAVA aggregate --Collection Interface

         This article was first published in cartoon The blog of      Reprint please indicate the source :      It is also said in the overview that :Collection yes jav ...

  6. 「 Explain profound theories in simple language 」java aggregate Collection and Map

    This series of articles focuses on java Set framework for a simple introduction , Make everyone right java There's a deep understanding of set . This article mainly introduces Collection Interface ,Map Interface and Collection The three sub interfaces of the interface Set ...

  7. java: aggregate collection

    collection Is the root interface in the collection hierarchy , Some collections allow repeating elements , And other sets don't allow . There are some collection Is ordered , And others are out of order . JDK No direct implementation of this interface is provided : It provides a more specific sub interface ...

  8. Java aggregate Collection、Set、Map、 Generic Brief notes

    aggregate What is a collection Concept Object's container , It implements the common operations on objects The difference with arrays Array length is fixed , The set length is not fixed Arrays can store basic types and reference types , A collection can only store reference types Location java.util.*; Colle ...

  9. Java aggregate Collection—— Beginners reference , Experts should be careful ( To be continued )

    1. Set introductions and examples Collection, aggregate . Similar to the set in the mathematical definition , Put a lot of elements in one container , So that we can store the results / Search and so on . Collection A set is actually an abstraction of many formal sets . For example, the 19th National Congress of the CPC ...

Random recommendation

  1. python-open Document processing

    python Built in functions open() Used to open files and create file objects grammar open(name[,mode[,bufsize]]) name: file name mode: Specifies the open mode of the file r: read-only w: write in a: additional ...

  2. Use javascript Open a new page without being blocked by the browser

    Use javascript There are several ways to open a new page , But each has its advantages and disadvantages , Here's an analysis This is the most common method for novices , The advantage is that it's easy to use , Disadvantage , It's simple , It will be intercepted by many browsers, resulting in loss of function ...

  3. 03- Shell Script learning -- Strings and arrays

    character string The string is shell The most commonly used and useful data types in programming ( Besides numbers and strings , There is no other type to use ), Strings can be in single quotes , You can also use double quotes , You can also use no quotes . The difference between single and double quotation marks is PHP similar : The difference between single and double quotation marks : double ...

  4. In depth analysis of Oracle 10g in SGA_MAX_SIZE and SGA_TARGET Differences and functions of parameters

    Link to the original text : SGA_MAX_SIZE It's from 9i It's something that's been set up since then SGA A parameter of size , and SGA_TARGET be ...

  5. ffmpeg + sdl -03 Simple audio player implementation

    Can't , I have encountered problems in my work . at present NEC EMMA The architecture of is as follows : from USB Read in file -> File analysis and extraction Packet Medium Payload Data   -> NEC HANDLE AVTrans ...

  6. Luogu - The matchstick equation -NOIP2008 Improve the group rematch

    Title Description Description Here you are. n A matchstick , How many shapes can you spell “A+B=C” The equation of ? In the equation A.B.C It's a whole number with a matchstick ( If the number is not zero , The highest position cannot be 0). Number with a matchstick 0-9 The spelling is shown in the picture : ...

  7. Move App Crash The design of test cases for

    Some common trigger moves App Crash Test scenario for , as follows : 1. Verify that there are different screen resolutions , operating system And operators on multiple devices App Behavior . 2. Verify with the newly released version of the operating system App act . 3. Verification in Tunnel ...

  8. ios Development - The boot page implements

    Source code : You can see demo, It's simple , I ...

  9. DOS Command basis , Inclusion DOS Library instructions

    20 Kind of commonly used DOS Summary of commands author : typeface :[ increase Reduce ] type : Reprint   DOS There are about a hundred orders in all ( Including text editing . Kill the virus . The configuration file . Batch processing, etc ), Let's introduce in detail 20 commonly used DOS command     First of all ...

  10. [Pytorch]Pytorch Detail record ( turn )

    Source of the article 1. PyTorch For training and testing, specify the instantiated model The model is :train/eval eg: ...