JAVA learning - collection, collection, traversal collection

gather

collection architecture

collection collection overview

Is the top-level interface of a singleton collection, which represents a set of objects
JDK does not provide a direct implementation of such collections, it provides more specific sub-interfaces (such as set and list) implementation

Create collection objects

Polymorphic way, concrete implementation class Arraylist etc.

collection of common methods
Code example:


    Collection<String> co = new ArrayList<String>();
        co.add("hello");
        co.add("hahah");
        co.remove("hello");
//        co.clear();
        System.out.println(co.isEmpty());
        System.out.println(co.size());

//        System.out.println(co.add("hello"));
        System.out.println(co);

collection traversal

Iterator: Iterator; collection-specific traversal method
. The next method can get the next element of the collection;
hasNext method, confirm whether there is a next element in the collection;

You can use this method +while to traverse the collection

Above code:

        Iterator<String> it = co.iterator();//得到迭代器
        while(it.hasNext()){
    
    //如果集合中还有下一个元素就执行
            String s = it.next();//获取下一个元素
            System.out.println(s);

instance of the student object

create student class

package collectiondemo;

public class student {
    
    
    private String name;
    private int age;
    public student(){
    
    
    };
    public student(String name, int age){
    
    
        this.name=name;
        this.age=age;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }
}

Create and iterate over the students collection

package collectiondemo;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class demo {
    
    
    public static void main(String[] args) {
    
    
        Collection<student> c = new ArrayList<student>();
        student s1 = new student("haha",20);
        student s2 = new student("yoyo",20);
        c.add(s1);
        c.add(s2);
        Iterator<student> it = c.iterator();
        while (it.hasNext()){
    
    
            student s =it.next();
            System.out.println(s.getName()+","+s.getAge());
        }


    }
}

Guess you like

Origin blog.csdn.net/weixin_52723971/article/details/110549896