1.集合与数组的转换
1.集合转换成数组
import javax.swing.text.html.parser.Entity;
import java.util.*;
public class Text{
public static void main(String[] args) {
ArrayList al=new ArrayList();
al.add("hi");
al.add("hii");
Object[] obj=al.toArray();
for (Object object:obj){
System.out.println(object);
}
System.out.println("--------------------");
Object[] obj1=new Object[1];
obj1=al.toArray();//如果原数组大小不足集合大小则以集合中元素的个数为准
for (Object object:obj1){
System.out.println(object);
}
}
}
效果图:
2.数组转换成集合
import java.util.Arrays;
import java.util.List;
public class Text{
public static void main(String[] args) {
String [] array={"hi","hii","hiii"};
List list= Arrays.asList(array);
System.out.println(list);
System.out.println("--------------");
String [] array2={"hi","hii","hiii"};
List list2=Arrays.asList(array2);
System.out.println(array2);
}
}
效果图:
2.Collections工具类的使用
专门用来操作集合的工具类
构造方法私有,禁止创建对象
提供一系列静态方法实现对各种集合的操作
具体操作:搜索、复制、排序、线程安全化等
1.Collections.addAll(list, “aaa”,“bbb”,“ccc”,“ccc”)向集合中一次性添加多个元素
Collections.addAll(al,"hi","hii","aiii","jjjj","jjjsj");
2.排序
Collections.sort(al);
3.二分搜索
Collections.binarySearch(al,"hi");//-(插入点+1) 插入点:如果要将该数据插入集合,插入数据的位置
4.集合拷贝 注意:如果源集合.size()>目标集合.size() 就会出现IndexOutOfBoundsEcception
Collections.copy(al,al2);
//注意:如果源集合.size()>目标集合.size() 就会出现IndexOutOfBoundsEcception
5.填充
Collections.fill(al,"aaaa");
6.最大
Collections.max(al);
7.最小
Collections.min(al);
8.逆序
Collections.reverse(al);
9.线程同步
List list=Collections.synchronizedList(al);
10.整合代码
import java.util.*;
public class Text{
public static void main(String[] args) {
ArrayList al=new ArrayList();
//向集合中一次性添加多个元素
Collections.addAll(al,"hi","hii","aiii","jjjj","jjjsj");
System.out.println(al);
//排序
Collections.sort(al);
System.out.println(al);
//二分搜索
System.out.println(Collections.binarySearch(al,"hi"));
System.out.println(Collections.binarySearch(al,"i"));//-(插入点+1) 插入点:如果要将该数据插入集合,插入数据的位置
ArrayList al2=new ArrayList();
//集合拷贝 注意:如果源集合.size()>目标集合.size() 就会出现IndexOutOfBoundsEcception
Collections.copy(al,al2);
System.out.println(al2);
//填充
Collections.fill(al,"aaaa");
System.out.println(al);
//最大
System.out.println(Collections.max(al));
//最小
System.out.println(Collections.min(al));
//逆序
Collections.reverse(al);
System.out.println(al);
//线程同步
List list=Collections.synchronizedList(al);
}
}
效果图:
转载:https://blog.csdn.net/qq_45017999/article/details/106002737
查看评论