180 likes | 306 Views
集合框架的使用. 集合框架定义. 所谓框架就是一个类库的集合。集合框架就是一个用来表示和操作集合的统一的架构,包含了实现集合的类与接口。. Collection 接口 2-1. Collection 对象是将多个元素组成一个单元的对象 集合用于存储、检索和操纵数据 集合框架是用于表示和操纵集合的统一体系结构. 算法. 接口. 是对实现接口的对象执行计算的方法. 是表示集合的抽象数据类型. 实现. 是接口的实际实现. Collection 接口 2-2. 集合框架包含三个组件. 集合框架的优点. 提供有用的数据结构和算法,从而减少编程工作
E N D
集合框架定义 所谓框架就是一个类库的集合。集合框架就是一个用来表示和操作集合的统一的架构,包含了实现集合的类与接口。
Collection 接口 2-1 • Collection对象是将多个元素组成一个单元的对象 • 集合用于存储、检索和操纵数据 • 集合框架是用于表示和操纵集合的统一体系结构
算法 接口 是对实现接口的对象执行计算的方法 • 是表示集合的抽象数据类型 实现 是接口的实际实现 Collection 接口 2-2 集合框架包含三个组件
集合框架的优点 • 提供有用的数据结构和算法,从而减少编程工作 • 提高了程序速度和质量,因为它提供了高性能的数据结构和算法 • 允许不同 API 之间的互操作,API之间可以来回传递集合 • 可以方便地扩展或改写集合
ArrayList 2-1 1 25 • ArrayList 对象是长度可变的对象引用数组,类似于动态数组 • 继承 AbstractList 并实现 List 接口 • 随着元素的添加,元素的数目会增加,列表也会随着扩展 • 访问和遍历对象时,它提供更好的性能
ArrayList 2-2 • ArrayList 类的构造方法包括:
示例 • import java.util.ArrayList; • class A{ • int m=0; • A(int m ){ this.m=m;} • int getM(){return m;} • } • public class Test{ • public static void main(String[] s) throws Exception{ • ArrayList listAll=new ArrayList(); • int tmp=0; • A a=null; • for(int i=0; i<4; i++){ • tmp=(int)(Math.random()*100); • a=new A(tmp); • listAll.add(a); • } • for(int i=0; i<listAll.size(); i++){ • a=(A)listAll.get(i); • System.out.println(a.getM()); • } • } • }
HashMap 2-1 • 实现了 Map 接口 • 用于存储键/值映射关系 • 不能保证其元素的存储顺序
HashMap 2-2 • 此类的构造方法包括: • 它在存放键/值时允许值为null 值
示例 • import java.util.HashMap; • class A{ • int m=0; • A(int m ){ this.m=m;} • int getM(){return m;} • } • public class Test{ • public static void main(String[] s) throws Exception{ • HashMap mapAll=new HashMap(); • int tmp=0; • A a=null; • for(int i=0; i<4; i++){ • tmp=(int)(Math.random()*100); • a=new A(tmp); • mapAll.put("00"+i,a); • } • for(int i=0; i<mapAll.size(); i++){ • a=(A)mapAll.get("00"+i); • System.out.println(a.getM()); • } • } • }
获取HashMap的keys • import java.util.HashMap; • import java.util.Iterator; • import java.util.Set; • public class Test{ • public static void main(String[] s) throws Exception{ • HashMap mapAll=new HashMap(); • int tmp=0; • A a=null; • for(int i=0; i<4; i++){ • tmp=(int)(Math.random()*100); • a=new A(tmp); • mapAll.put("00"+i,a); • } • Set set=mapAll.keySet(); • Iterator iter=set.iterator(); • Object key=null; • while(iter.hasNext()){ • key = iter.next(); • a = (A)mapAll.get(key); • System.out.println(a.getM()); • } • } • }
Vector 类 它具有类似数组的数据 结构,而且是动态的 可以存放一定 数量的元素 容量可以递增 Vector 类 3-1
示例 • import java.util.Vector; • class A{ • int m=0; • A(int m ){ this.m=m;} • int getM(){return m;} • } • public class Test{ • public static void main(String[] s) throws Exception{ • Vector vecAll=new Vector(); • int tmp=0; • A a=null; • for(int i=0; i<4; i++){ • tmp=(int)(Math.random()*100); • a=new A(tmp); • vecAll.add(a); • } • for(int i=0; i<vecAll.size(); i++){ • a=(A)vecAll.get(i); • System.out.println(a.getM()); • } • } • }
作业 • 假如有以下email数据“aa@sohu.com,bb@163.com,cc@sina.com,..”现需要把email中的用户部分和邮件地址部分分离,分离后以键值对应的方式放入HashMap • 产生一组班级对象,并放入集合ArrayList对象中