Java study notes 13 collection

gather

It is possible to save multiple objects through an array in the program, because the length of the array is immutable. Some special classes are provided in JDK, these classes can store any object, and the length is variable, and these classes are called collections in java. The collection classes are located in the java.util package.

Collection interface

method declaration Functional description
boolean add(Object o) add an element to the set
boolean addAll(Collection c) Add a collection (multiple elements)
void clear() empty collection
boolean remove(Object o) removes an object (element) from the collection
boolean removeAll(Collection c) delete a collection (multiple elements)
boolean isEmpty() is it empty
boolean contains(Object o) Determine whether the collection has this element
boolean containsAll(Collection c) Determine whether there is a parameter set in the set
Iterator iterator() returns a traversal iterator
int size() Returns the number of elements in the collection

List interface

method declaration Functional description
void add(int index,Object element)
boolean addAll(int index,Collection c)
Object get(int index)
Object remove(int index)
Object set(int index,Object element)
int indexOf(Object o)
int lastIndexOf(Object o)
List subList(int fromIndex,int toIndex)

The difference between ArrayList and LinkedList

ArrayList retrieves data fast. (Larger usage);
LinkedList adds data quickly.

Traversal is faster than for loop.

easy to use


		List<Integer> list = new ArrayList<>();
        list.add(12);
        list.add(0, 22);
        System.out.println(list);
        list.addAll(List.of(1, 2, 3, 4, 5, 2, 3, 3, 41));
        System.out.println(list);


        //移除元素2
        Integer i = 2;
        boolean f = list.remove(i);
        System.out.println(f);
        System.out.println(list);


        //移除第二个元素 下标从零开始。
        System.out.println(list.remove(1));
        System.out.println(list);


        System.out.println("=================================");


        //判断集合中有没有41
        System.out.println(list.contains(41));


        //判断集合和集合 List.of():快速声明一个数组
        System.out.println(list.containsAll(List.of(1, 2, 3)));
        Collections.reverse(list);
        
			//查看集合的大小
        System.out.println(list.size());
        


        for (int a1 : list) {
    
    
            System.out.printf("list[%d]=%d ", list.indexOf(a1), a1);
        }
        System.out.println();


        for (int j = 0; j < list.size(); j++) {
    
    
            System.out.printf("list[%d]=%d ", j, list.get(j));
        }
        System.out.println();

        //使用迭代器遍历
        Iterator<Integer> it = list.listIterator();
        while (it.hasNext()) {
    
    
            System.out.println(it.next());
        }

Guess you like

Origin blog.csdn.net/xxxmou/article/details/129171143
Recommended