Java study notes-Collections use

Collections are operations performed on lists.

1. The method is as follows:

void reverse(List list): reverse

void shuffle(List list), random sort

void sort(List list), sort in ascending order of natural sort

void sort(List list, Comparator c);Customized sorting, the sorting logic is controlled by Comparator

void swap(List list, int i, int j), swap the elements at two index positions

void rotate(List list, int distance), rotate. When distance is a positive number, move the distance elements after the list to the front as a whole. When distance is negative, move the first distance elements of the list to the back as a whole.

 

2. Test the code

public class Test {

    public static void main(String[] args) {
        int[] num=new int[]{1,3,2,6,8,9};
        List<Integer> list=new ArrayList<>();
        for(int i=0;i<num.length;i++){
            list.add(num[i]);
        }

        //升序排序
        Collections.sort(list);

        //反转list
        Collections.reverse(list);

        //交换两个索引位置的元素
        Collections.swap(list,1,3);
        
        for(int j=0;j<list.size();j++){
            System.out.println(list.get(j));
        }
    }
}

 

Guess you like

Origin blog.csdn.net/mumuwang1234/article/details/112665581
Recommended