


版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、java第七章容器(可编辑)(文档可以直接使用,也可根据实际需要修改使用 ,可编辑推荐下载)六节:容器1. 容器API Jdk所提供的容器位于java.util 包内左边:一个一个往里装右边:一对一对往里装Collection:容器(分了两子接口)Map:定义存储“1. set :无顺序,不重复(如数学集合)键(key)-值(value)映射对”无下标,只能用Iterator逐一遍历的方法2. l ist :有顺序,可重复(两数eauals即算重复)按先来后到的顺序排序 有卜标 collecti on 接口中所定义的方法:add ():方法添加remove():删去方法(重要)importpu
2、blic class un iltset public static voidmain( Stri ng args) Collectio n c =new ArrayList();c.add( "hello" );c.add( new date1(2021,12,29);/c只能用collection 类的方法/此包Str in gtest2里已有date1 类c.add( new In teger(100);/ c.add( int i=100);装对象是错的,因为int是存放在栈内存里的,会随时清空,只能System.out .println(c.size();Syst
3、em.out .println(c);c.remove("hello" ); /hello被去掉,String 对象在date segment内存里一样字符为同一对象(数据内存里的节约办法)c.remove(new Integer(100);100 被去掉,Integer类重写了 equals 方法,只要值相同,对象视为相同System.out .println(c.remove(new date1(2021,12,29);/false2021 12 29 未被去掉, 不是同一对象System.out .println(c);结果:3(collecti on的对象打印时的格
4、式)hello, 2021 12 29, 100false2021 12 29为了使两个对象也能相等,现在重写 datel里的equals方法,注意重写equals 方法应要重写hashcode方法(当类的对象当做索引时会用hashcode方法)class date1String year , month , day ;date1(String y,String m,String day)yearmon th = m;this . day = dapublicStri ng toStri ng()returnyear +" " +month +" " +
5、day ;/此处开始重写date1类equals方法,供容器章目使用publicboolea nequals(Object obj)if (objinstanceofdate1)date1 d = (date1)obj;return(year . equals (d. year )&&( month =d. month )&&( day =d. day);、这里写equals方法必须是对象才能写,String是类,这里如果写int就错了,int是基本类型,没有方法returnsuper .equals(obj);(如果obj不是date1类的,就返回父类方法)p
6、ublic int hashCode()return year .hashCode(); /引索的date1对象这里则上个函数结果:2021 12 29去掉了接口(游标器,去遍历每个元2.1 terator素)所有实现了 Collection接口的容器类都有一个Iterator 方法用以返回一个实现了 Iterator 接口的对象Iterator对象称作迭代器,用以方便的实现对容器内元素的遍历操作Iterator 接口定义了如下方法:boolea n hasNext()判断游标右边是否有兀素Object n ext()返回游标右边的元素 并将游标游到下一个位置Void remove();删除游
7、标左面的元素,在执行完next1游标LT元素Next()之后该操作只能执行一次importclass n ameStringfirstName , lastNamen ame(Stri ng f,Str ing l)firstName = f; lastName = l;publicString toString()/ 重写 toStringreturn firstName +"," +lastName ;public class IteratorTest public staticvoidmain(String args) Collection c =newHashSet
8、();c.add(newname("f1", "l1" );c.add(newname("f2", "l2" );c.add(newname("f3", "l3" );Iterator i = c.iterator();while(i.hasNext()返回值为对象,要转换name n = (name)i.next(); /next()System. out .print(n.firstName +" " );System. out .println();
9、/ /c.add(new name("ffff4", "llll4"c.add(new name("f5" ,"l5" );c.add(new name("ffff6", "llll6"for (Iterator a = c.iterator();a.hasNext();););name na = (name)a.next();if (na. firstName .length()<3)循环中执行了锁定,只有a.remove(); / 删掉了 f1,f2,f3,f5 /
10、 不能写: c.remove(name); iteaatoriterator 对象能用System. out .print(c); 结果: f2 f1 f3ffff6,llll6, ffff4,llll43. 补充: Jdk1.5 增强的 for 循环增强的 for 循环对于遍历 array 或 Collection 的时候相当简 便缺陷:数组:不能方便的访问下标值集合:与使用iterator 相比,不方便的删除集合中内容总结:除了简单遍历并读出其中内容外,不建议使用增加 for例如:public class ZengQiangforTest /* param args*/public sta
11、tic void main(String args) int a=1,3,5,2,9,0,6;for ( int i:a)/ 把数组 a 里的元素拿出来放到 i 里System. out .print(i+ " " );结果: 1 3 5 2 9 0 64.Set 接口Set 接口是 Collection 的子接口, Set 接口没有提供额外的方法,但实现Set接口的容器类中的元素是没有顺序的,且不可重复Set 容器可以与数学中“集合”的概念相对应Set 容器类有 HashSet , TreeSetimportpublic class SetTest public stat
12、ic void main(String args) Set s =new HashSet();s.add( "hello" );s.add( "world" );s.add( new name( "f1" , "f2" );s.add( new Integer(100);方法才能/ 重复了,但不是同一对象,要在重写 name 类 equals 方法以及 hashcode 不显示s.add( new name( "f1" , "f2" );s.add( "hello&
13、quot; ); / 重复了,不显示System. out .println(s);结果: hello, 100, f1 f2, worldSet 里常用方法 :importpublic class SetTest2 public static void main(String args) Set s1 =new HashSet();Set s2 =new HashSet();s1.add( "a" );s1.add("b" );s1.add("c" );s2.add("a" );s2.add("b&qu
14、ot; );s2.add("d" );Set sn =new HashSet(s1); / 相当于把 s1 全部复制到 snsn.retainAll(s2);/ 1.retainAll求两 Set 交集System. out .println(sn); Set su = new HashSet(s1);su.addAll(s2); / 2.addAll求两 Set 并集System. out .println(su);结果: b, ad, b, c, a5. List 接口List 接口是 Collection 的子接口,实现 List 接口的容器类中的元素 是有顺序的 ,
15、而且 可以重复 。List 容器中的元素都 对应一个整数型 的序号记载其在容器中的位 置,可以根据序号存取容器中的元素( 相当于数组,但可加新元 素)。J2SDK 所提供的 List 容器类有 ArrayList , LinkedList 等。相关方法:importpublic class ListTest public static void main(String args) List l1 =new ArrayList();for ( int i = 0;i<=5;i+)l 1.add( "a" +i);System. out .println(l1);l1.a
16、dd(3, "a100" ); / 1.void add(int index,Objectelement) 方法,在第3个位置添一个 String 类型字符串(是对象,所以用 Obj ),原第3 位置向后退一个。 element (元素)System. out .println(l1);element) 方法, 把第 6个位置换成阿 a200System. out .println(l1);System. out .println(String)l1.get(2); / 3. Object get (ine index)方法 ,得到第 2 个位置对象System. out
17、.println(l1.indexOf( "a3" ); / 4.int indexof (object o)方法 ,引索得到 a3 是第几个位置l1.remove(1); / 去掉第 1 该位置上的数System. out .println(l1);List 常用算法 :类提供了一些静态方法实现了基于 List 容器的一些常用算法void sort(List)对 List 容器内的元素排序void shuffle(List)对 List 容器内的对象进行随机排列void reverse(List)对 List 容器内的对象进行逆序排列void fill ( List,ob
18、ject)用一个特定的对象重写整个 List 容器void copy (List dest,List src)将 src List 容器内容拷贝到 dest List容器Int binarySearch(List,object) 对于顺序的 List 容器,采用折半查找 的方法查找特定对象importpublic class ListTest2 public static voidmain(String args) List l1 =new LinkedList();List l2 =new LinkedList();for ( int i =0;i<10;i+)l1.add("
19、;a" +i);System. out.println(l1);Collections.shuffle(l1);/ 随机排序System. out.println(l1);Collections.reverse(l1);/ 逆序System. out.println(l1);Collections.sort (l1);/排序System. out.println(l1);System. out.println(Collections.binarySearch(l1, "a5" ); / 二分法查找6 parable 接口上面程序里 Collections 里的 s
20、ort 方法:列表中的所有元素都必须实现Comparable 接口;对象要继承comparable接口Comparable接口中只有一个方法Public int compareTo (Object obj): 返回 0 (this = obj)返回正数( this>obj); 返回负数( this<obj)importclass name implements Comparable / 对象要继承 comparable 接口String firstName , lastName ; name(String f,String l) firstName = f; lastName =
21、l;public String toString() / 重写 toStringreturn firstName +" " +lastName ; public boolean equals(Object obj) if (obj instanceof name) name a = (name)obj; returnfirstName .equals(a. firstName )&& lastName .equals(a. lastName ); return super .equals(obj);public int hashCode()return fi
22、rstName .hashCode();public int compareTo(Object o) name n = (name)o;int panduan = lastName 可直接比较/ 重写 compareTo 方法pareTo(n. lastName ); /lastName是 Stringreturn (panduan!=0? panduan:firstNamepareTo(n.firstName );importpublic class ComparableTest public static void main(String args) List l1 =new Linked
23、List();l1.add(l1.add(l1.add(l1.add( System.new name ( "haifeng" , "wang" ); new name( "nan" , "kang" );new name( "xiaohui" , "liu" ); new name ( "dafeng" , "wang" ); out .println(l1);Collections. sort (l1);System.out .pr
24、intln(l1);结果: haifeng wang, nan kang, xiaohui liu, dafeng wang nan kang, xiaohui liu, dafeng wang, haifeng wang7. 如何选择数据结构:衡量标准:读的效率和改的效率Array 读快改慢 (数组类型的,系统读起来快,改起来慢 )Linked 改快读慢Hash 两者之间8.Map 接口:实现Map接口的类用来存储 键一值 对。(把一个对象里的一个元素为键,其他为值)Map接口的实现类有 HashMap和TreeMap等。Map类中存储的 键一值 对 通过键来标识,所以 键值不能重复常用方法
25、:1. Object put( Object key,Object value);放置方法,通过key找到KeyalueValue这个对象后,把value替换原来的value,原value被返回System. out .println(m1.size();/ 2.int size() 方法,求共装importpublic class MapTest public static void main( Stri ng args) Map m1 =new HashMap();Map m2 =new TreeMap();m1.put( "one" , new Integer(1);
26、/ 键和值 都要是对象m1.put("o ne",1); jdk1.5以后可以这样写自动转换成值对象,叫自动打m1.put("two" , new In teger(2);m1.put("three" , new In teger(3);m2.put( "A" , new Integer(1);m2.put( "B" , new Integer(2);了多少 对 对象System. out .println(m1.containsKey( "one" ); / 3.boole
27、an containKey(Object key)方法,是否包含这个 leySystem. out .println(m2.containsValue( newInteger(1); / 4.boolean containValue ( Object Value ), 是否包含这个 valueif (m1.containsValue( new Integer(1)int i = (Integer)m1.get("two" ).intValue(); / 5.Objectget (Object key )方法,通过key找到value 对象,再把他转成integer 对象通过
28、其 intValue 方法以 int 类型返回该值/int i = (integer)m1.get("teo");转换成 integer 类型后,对象可以自动转换成值,叫 自动解包System. out .println(i);Map m3 = new HashMap(ml); / 把ml全部给 m3m3.putAll(m2); /6. void putall ( Map t )方法,把另外一个Map里的所有东西都加进来System. out .println(m3);结果: 3truetrue2two=2, A=1, B=2, one=1, three=39Auto-bo
29、x ing/un box ing在合适的时机打包、解包(上面程序所提到的)自动将基础类型转换为对象自动将对象转换为基础类型例:原写法import java.叽匕丄;public class Test ArgsHords private static Xinal Intent ONE = new Integer (1);public static void mainfSti:ing args) Map m - new HashMap();feu (inc i = 0; i < args .length; i f- ) let亡口亡i: freq(Integer) m.get (argsi)
30、;m,put(jsi r(freq = null? CUE : neu Integer(freq,intValue() + 1); Ssrew.out. pr intln(w,size () + rr dL3.inct words det ected:rr);Syatem0口匕printIn(m);应用解包打包后:importpublicclass jishuTest one = 1;publicstatic finalIn tegerpublic static voidmain( Stri ng args) Map m = new HashMap();int geshu =(Integer)m.get(argsi)=null?0:(lnteger)m.get(argsi);x 写这个判断 是因为本来get方法是得到对象value为null,这样通过判断能可以返回0one : geshu+1);个被找到“);m.put(argsi, (geshu = 0? System. out .println(m.size()+ System. out .println(m);D:JleimTeet &球bbb cce dd 去畝球bbb dd4个被找到结果:ccgI bbb=2>10
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 纤维原料在冶金行业中的应用考核试卷
- 管道工程环境保护法律法规政策研究与探讨考核试卷
- 纺织品在家居绿植养护的创新考核试卷
- 纺织品物流配送考核试卷
- 老年营养与餐饮服务考核试卷
- 生物农药田间试验与农业人才培养合同
- 大型综合体建筑工程质量监管及综合评价协议
- 高效流水线工人岗位竞聘及劳务派遣合同
- 智能家居全屋定制智能家居系统集成与施工一体化服务合同
- 区块链矿机网络交换机租赁与智能化升级合同
- 财务岗位招聘笔试题及解答(某大型国企)2025年
- 第六次全国幽门螺杆菌感染处理共识报告-
- 电影与幸福感学习通超星期末考试答案章节答案2024年
- 屋顶分布式光伏项目可行性研究报告
- 农业综合执法大比武测试题
- 时花采购供应投标方案(技术方案)
- 专题14 阅读理解七选五-【好题汇编】五年(2020-2024)高考英语真题分类汇编
- 国开《Windows网络操作系统管理》形考任务5-配置DNS服务实训
- 创业管理(上海财经大学)智慧树知到期末考试答案章节答案2024年上海财经大学
- 高中物理必修二《动能和动能定理》典型题练习(含答案)
- 《公路桥涵施工技术规范》JTGT3650-2020
评论
0/150
提交评论