• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Foreordination
酒后高歌磨剑,梦中快意恩仇,名利脚下踩,情义两肩挑
博客园    首页    新随笔    联系   管理    订阅  订阅
一、集合框架(Collection和Collections的区别)

一、Collection和Map

是一个接口

Collection是Set,List,Queue,Deque的接口

Set:无序集合,List:链表,Queue:先进先出队列,Deque:双向链表

Collection和Map之间没有关系,Collection里放一个一个对象的,Map是放键值对key-value。

 

 

二、Collections

Collections是一个类,也就是容器的工具类,如同Arrays就是数组的工具类

里面有很多方法:

常用的:reverse():反转,逆序

shuffle():混淆,就跟洗牌一样,随机打乱顺序

sort():排序从小到大的顺序

swap():交换

rotate():向右滚动

package collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestCollection{
    public static void main(String[] args){
        //初始化集合
        List<Integer> num=new ArrayList<Integer>();
        for(int i=0;i<10;i++){
            num.add(i);
        }
        System.out.println("集合中的数据:");
        System.out.println(num);//0 1 2 3 4 5 6 7 8 9
        Collections.reverse(num);
        System.out.println("翻转后集合中的数据:");
        System.out.println(num);//9 8 7 6 5 4 3 2 1 0
        Collections.shuffle(num);
        System.out.println("混淆后集合中的数据:");
        System.out.println(num);//7 5 4 1 2 6 9 3 0 8
        Collections.sort(num);
        System.out.println("排序后集合中的数据:");
        System.out.println(num);//0 1 2 3 4 5 6 7 8 9
        Collections.swap(num,0,6);
        System.out.println("交换0和6位置的数据后,集合的数据为:");
        System.out.println(num);//6 1 2 3 4 5 0 7 8 9
        Collections.rotate(num,2);//向右滚动
        System.out.println("把集合向右滚动2个单位,集合中的数据为");//也就是把集合中最后面的两个数,放到最前面来。其余不变。
        System.out.println(num);//8 9 6 1 2 3 4 5 0
    }
}
View Code

synchronizedList():线程安全化

也就是把不安全线程转化为安全线程,比如ArrayList是不安全线程,在多线程中不能用,而Vector是多线程的安全。

package collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestCollection{
    public static void main(String[] args){
        List<Integer> num=new ArrayList<Integer>();
        System.out.println("把非安全线程的List转换为线程安全的List");
        Collections.synchronizedList(num);
    }
}
View Code

 

posted on 2018-02-28 11:59  Foreordination  阅读(289)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3