• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
阿呆草原狼
博客园    首页    新随笔    联系   管理    订阅  订阅
Java集合

1、三种代表体系:Set、List、Map。

2、主要由两个接口派生生出来:

3、Collection和Iterator接口

   Collection接口是List、Set和Queue接口的父接口,Collection接口操作方法如下:

  

package CollectionLearn;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;

public class TestCollection {
    public static void main(String[] args)
    {
        Collection c = new ArrayList();
        c.add("hunk");
        c.add(66);
        c.add(66);
        System.out.println(c.size());
        c.remove(66);
        System.out.println(c.size());
        System.out.println(c.contains("hunk"));
        c.add("now");
        System.out.println(c);
        Collection books = new HashSet();
        books.add("Java");
        books.add("now");
        System.out.println(c.containsAll(books));
        c.removeAll(books);
        c.clear();
        books.retainAll(c);
        System.out.println(books);
    }

}

 

 

Iterator接口,遍历集合元素,隐藏了各种collection的实现类的底层细节:

package CollectionLearn;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

public class TestIterator {
    public static void main(String[] args)
    {
        Collection books =new HashSet();
        books.add("hunk");
        books.add("huang");
        books.add("qj");
        Iterator it = books.iterator();
        while(it.hasNext()){
            String book = (String)it.next();
            System.out.println(book);
            if(book.equals("hunk")){
                it.remove();

                //下面这句是错误的
                //book.remove("qj");
            }

           //Iterator 只复制值,下面的赋值是无效的
            book="test";
        }
        System.out.println(books);
    }

}

4、使用foreach循环遍历集合元素。

   

 

5、Set接口:

  

5.1 HashSet:不能保证元素的顺序,顺序可能发生变化;HashSet不是同步的,多个线程修改HashSet;必须通过代码来同步。集合元素值可以为null。

   

   

posted on 2015-04-23 17:39  阿呆草原狼  阅读(143)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3