About the array operation
4.Collections and
the tool class in the Arrays collection framework: Features: The methods in this tool class are all static.
Collections: Common methods:
1. Perform a binary search on the list:
the premise is that the collection must be ordered.
int binarySearch(list,key); Commonly used to find the index of the element (with natural order)
//The list must be upgraded and sorted according to the natural order of the elements
//The elements in the list collection are required to be subclasses of Comparable.
int binarySearch(list,key,Comparator); If it is a custom class to find the index of the key, the comparator key is key
2, and the list collection is sorted.
sort(list);
//To sort the list, in fact, the compareTo method of the objects in the list container is used
sort(list, comaprator); Commonly used
// Sort 3 according to the specified comparator, and
take the maximum or minimum value for the set . Commonly used
max(Collection) max(Collection, comparator) min(Collection) min(Collection, comparator) 4
without natural order, invert the list collection. reverse(list); no need to pass a comparator because there is no comparison process
5. Forcibly reverse the comparison method.
Comparator reverseOrder();
Comparator reverseOrder(Comparator);
6. Perform position replacement on the elements in the list collection.
swap(list,x,y);
7, replace the elements of the list set. If the replaced element does not exist, the original set is unchanged.
replaceAll(list,old,new);
8, you can turn an unsynchronized collection into a synchronized collection.
This is achieved by adding a synchronized synchronization lock to the method. We know that synchronized locks have high overhead and are not recommended for use in programs.
Set synchronizedSet(Set s)
Map synchronizedMap(Map
import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
class Demo1
{
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(4);
list.add(3);
list.add(1);
list.add(2);
list.add(3);
// 排序
Collections.sort(list);
// 折半查找的前提是排序好的元素
System.out.println( Collections.binarySearch( list , 8 ) ); // 找不到返回-插入点-1
// 反序集合输出
Collections.reverse( list );
System.out.println( list );
// 求最值
System.out.println( Collections.max( list ) ); // 4
// fill() 使用指定的元素替换指定集合中的所有元素
// Collections.fill( list, 5 );
System.out.println( list );
// 将数组转换为集合
Integer is[] = new Integer[]{6,7,8};
List<Integer> list2 = Arrays.asList(is);
list.addAll( list2 );
System.out.println( list );
// 将List转换为数组
Object [] ins = list.toArray();
System.out.println( Arrays.toString( ins ) );
}
}