Java learning - List collection, enhanced for

List collection

list
An ordered collection (also known as a sequence). Users of this interface have precise control over where each element in the list is inserted. Users can access elements by integer index (position in the list), and search for elements in the list.
Unlike sets, lists generally allow duplicate elements.

List inherits from Collection, and Collection has methods List has;

Specific methods of the List collection

A special collection of list collections
The list can modify the element at the specified position;
the list can also be traversed through the get method;
the above code:

        List<String> list = new ArrayList<String>();
        list.add("haha");
        list.add("hello");
        list.add(1,"yoyo");
        list.add(3,"hoho");
        list.remove("haha");
        list.remove(2);
        list.set(0,"love");
        System.out.println(list.get(0));
        System.out.println(list);
//        Iterator it = list.iterator();
//        while (it.hasNext()){
    
    
//            Object s = it.next();
//            System.out.println(s);
//        }
        for(int i=0;i<list.size();i++){
    
    
            String s =list.get(i);
            System.out.println(s);
        }

enhanced for

Simplify the traversal of arrays and collections:
classes that implement the Iterable interface allow their objects to become targets of enhanced for statements. The
internal principle is an Iterable iterator
Enhance the format of for
Code example

        for(String sj : set){
    
    //sj是变量名
            System.out.println(sj);//遍历的过程,这里可以增加需要在遍历过程中进行的其他操作
        }

Guess you like

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