![Java习惯用法总结-编程小技巧_第1页](http://file2.renrendoc.com/fileroot_temp3/2021-11/10/546b4029-8156-40cf-89ce-9a099111e3f0/546b4029-8156-40cf-89ce-9a099111e3f01.gif)
![Java习惯用法总结-编程小技巧_第2页](http://file2.renrendoc.com/fileroot_temp3/2021-11/10/546b4029-8156-40cf-89ce-9a099111e3f0/546b4029-8156-40cf-89ce-9a099111e3f02.gif)
![Java习惯用法总结-编程小技巧_第3页](http://file2.renrendoc.com/fileroot_temp3/2021-11/10/546b4029-8156-40cf-89ce-9a099111e3f0/546b4029-8156-40cf-89ce-9a099111e3f03.gif)
![Java习惯用法总结-编程小技巧_第4页](http://file2.renrendoc.com/fileroot_temp3/2021-11/10/546b4029-8156-40cf-89ce-9a099111e3f0/546b4029-8156-40cf-89ce-9a099111e3f04.gif)
![Java习惯用法总结-编程小技巧_第5页](http://file2.renrendoc.com/fileroot_temp3/2021-11/10/546b4029-8156-40cf-89ce-9a099111e3f0/546b4029-8156-40cf-89ce-9a099111e3f05.gif)
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、java习惯用法总结在java编程中,有些知识并不能仅通过语言规范或者标准api文档就能学 到的。在木文中,我会尽量收集一些最常用的习惯用法,特别是很难猜到的用法。 (joshua bloch的effective java对这个话题给出了更详尽的论述,可以 从这本书里学习更多的用法。)java我把本文的所有代码都放在公共场所里。你可以根据自己的喜好去复制和修 改任意的代码片段,不需要任何的凭证。目录实现:o equals()o hashcode()o compareto()o clone() 应用:o stringbuilder/stringbuffero random.nextlnt(int
2、)o iterato r.remove()ostringbuilde r.re vcrse()o thread/runnableo try-finally输入/输出:o从输入流里读取字节数据o从输入流里读取块数据o从文件里读取文本o向文件里写文木预防性检测:o数值o对象o数组索引o数组区间 数组:o填充元素o复制一个范围内的数组元素o调整数组大小包装o个字节包装成一个into分解成4个字节实现 equals ()class person string namc;int birthyear;byte raw;public boolean equals(object obj) if (!obj i
3、nstemccof person) return false;person other 二(person)obj; return name. equals(other, name)&& birthycar 二二 other.birthyear&& arrays, equals(raw, other, raw);public int hashcode() 参数必须是object类型,不能是外伟i类。 foo.equals(null)必须返回 false,不能抛 nullpointerexceptiono (注意,null instanceof 任意类 总是返回fa
4、lse,因此上而的代码可以运行。) 基本类型域(比如,int)的比较使用=,基木类型数组域的比较使用arrays.equals()o 覆盖equals()时,记得要相应地覆盖hashcode(),与equals()保持致。 参考:java.lang.object.equals(object)。实现 hashcode ()class person string a;object b;byte c;int d;public int hashcode() return a. hashcode () + b. hashcode () + c + arrays. hashcode (d);public
5、boolean equals (object o) 当x和y两个对彖具有x.equals(y) = true ,你必须要确保x.hashcode()= y.hashcodc()e 根据逆反命题,如果 x.hashcode() != y.hashcode(),那么 x.equals(y) = false 必定成 立。 你不需要保证,当 x.equals(y) = false 时,x.hashcode() != y.hashcode()o 但是,如果 伤可以尽可能地使它成立的话,这会提高哈希表的性能。 hashcode()最简单的合法实现就是简单地return 0;虽然这个实现是正确的,但是这 会
6、导致hashmap这些数据结构运行得很慢。 参考:java.lang.object.hashcode()。实现 compareto ()class person implcments comparablc<pcrson> string firstname;string lastname;int birthdate;/ compare by firstnamc, break tics by lastnamc, finally break tics by birthdatepublic int compareto(person other) if (firstname. compare
7、to(other. firstname) !二 0) return firstname. compareto(other. firstname);else if (lastname. compareto(other. lastname) != 0) return lastname. compareto(other, lastname);else if (birthdate < other, birthdate)return t;el se if (birthdate > other, birthdate)return 1;elsereturn 0; 总是实现泛型版本comparab
8、le iflj不是实现原始类型comparable。因为这样对以 节省代码量和减少不必要的麻烦。只关心返回结果的正负号(负/零/正),它们的大小不重要。 cpareo的实现与这个类似。参考:java.lang.comparableo实现 clone ()class values implements cloneable string abc;double foo;int bars;date hired;public values clone() try values resu it 二(values) super, cl one ();result, bars 二 result, bars,
9、clone();result, hired = result, hired, clone (); return result; catch (clonenotsupportedexception e) / impossiblethrow new assertionerror(e);ij 使用super.clone()让objcc(类负责创建新的对彖。基本类型域都己经被正确地复制了。同样,我们不需要去克隆string和biginteger 等不可变类型。手动对所有的非基木类型域(对象和数组)进行深度复制(deep copy)o 实现了 cloneable 的类,clone()方法永远不要抛 cl
10、onenotsupportedexception0 因此, 需要捕获这个异常并忽略它,或者使用不受检异常(unchecked exception)包装它。 不使用object.clone()方法而是手动地实现clone()方法是可以的也是合法的。 参考:javaangobject.clone()、java.lang.cloneab!e()使用 stringbuilder 或 stringbuffer/ join("a", b", c) -> ,za and b and cstring join(list<string> strs) stringb
11、uilder sb 二 new stringbuilder();boolean first 二 true;for (string s : strs) if (first) first = false; else sb. append (,z and “); sb.append (s);rcturn sb. tostring();不要像这样使用垂复的字符串连接:s += item ,因为它的时间效率是o(22)。 使用stringbuilder或者stringbuffer时,对以使用append。方法添加文本和使用 tosting()方法去获取连接起来的整个文札 优先使用stringbuilde
12、r,因为它更快。stringbuffer的所有方法都是同步的,而你通 常不需要同步的方法。 参考 java.lang.stringbuilder> javaang.stringbuffer。生成一个范围内的随机整数random rand = new random ();/ between 1 and 6, inelusiveint diceroll () rcturn remd. ncxtlnt (6) + 1;总是使用java api方法去生成一个整数范围内的随机数。 不要试图去使用math.abs(rand.nextlnto) % n这些不确定的用法,因为它的结果是 冇偏差的。此外,
13、它的结果值冇可能是负数,比如当rand.ncxtlnt()= integer.min_value 时就会如此。 参考:java.util.random.nextlnt(int)c使用 iterator remove ()void filter(list<string> list) for (lterator<string> iter = listiterator() ; iterhasnext(); ) string item = iter, next ();if (.)iter. remove(); remove。方法作用在next()方法最近返回的条h上。每个条h只
14、能使用一次remove() 方法。 参考:java.util.iterator.remove()0返转字符串string reverse(string s) return new stringbuiider (s). reverse()tostring(); 这个方法口j能应该加入java标准库。 参考:java.lang.stringbuilde匚reverse。启动一条线程下而的三个例子使用了不同的方式完成了同样的事情。实现runnnable的方式:void startathreado() new thread (new myrurrnable (). start();class myru
15、nnable implements runnable public void run() 继承thread的方式:void startathrcadl() new mythread(). start ();class mythread extends thread public void run()匿名继承thread的方式:void startathread2() new thread () public void run() start (); 不耍直接调用run()方法。总是调用thread.start()方法,这个方法会创建一条新的线 程并使新建的线程调用run()o 参考:javaa
16、ng.thrcad, javaang.rurmablc。使用 try-finallyi/o流例子:void writcstuff() throws ioexccption outputstream out = new fi1eoutputstream();try out. write (.); finally out. closeo ;锁例子:void dowithlock(lock lock) lock. acquire ();try finally lock, release ();如果try之前的语句运行失败并且抛出异常,那么finally语句块就不会执行。但无 论怎样,在这个例子里不用
17、担心资源的释放。如果try语句块里面的语句抛出界常,那么程序的运行就会跳到finally语句块里执 行尽可能多的语句,然后跳出这个方法(除非这个方法还冇另一个外围的finally语 句块)。从输入流里读取字节数据inputstrcam in =(); try while (true) int b = in. read(); if (b = -1)break;(process b) finally in. close (); read()方法要么返回下-次从流里读取的字节数(0到255,包括0和255),要么在 达到流的末端时返冋参考:java.io.inputstream.read()o从输入
18、流里读取块数据inputstream in =(.);try byte buf = new byte100;while (true) int n = in. read (buf);if (n 二二-1)break;( process buf with offset=0 and length二n ) finally in. close ();要记住的是,read()方法不一定会填满整个buf,所以你必须在处理逻辑中考虑返冋 的长度。 参考: java.io.inputstream.read(byte)> java.io.inputstream.read(byte, int, int)o从文
19、件里读取文本bufferedreader in = new bufferedreader (new inputstreamreader(new f订einputstream(. .), utf-8); try while (true) string line = in. readline();if (line = null)break;(process line) finally in. close (); bufferedreader对象的创建显得很兀长。这是因为java把字节和字符当成两个不同 的概念来看待(这少c语言不同)。 你可以使用任何类型的inputstream来代替filelnp
20、utstream,比如socketo 当达到流的末端时,bufferedreader.readline()会返回nullo 耍一次读取一个字符,使用reader.read()方法。你可以使用其他的字符编码而不使用utf-8,但最好不要这样做。 参考:java.io.bufferedreader> java.io.inputstreamreadero向文件里写文木printwriter out = new printwriter(new outputstrcamwritcr(new fiicoutputstrcam(),"utf8"); try out. print (
21、,zhello “);out. print (42);out.println( world!zz); finally out. close (); printwritcr对彖的创建显得很冗长。这是因为java把字节和字符当成两个不同的概 念来看待(这与c语言不同)。就像system.out,你可以使用print。和println()打印多种类型的值。你可以使用其他的字符编码而不使用utf-8,但最好不要这样做。 参考:java.io.printwriterjava.io.outputstreamwriter0预防性检测(defensive checking)数值int factorial(in
22、t n) if (n < 0)throw new 11 legalargumentexception (z,undefinect);else if (n >= 13)throw new arithmeticexception("result overflow");else if (n 二二 0)return 1;elsereturn n * factorial(n - 1);不要认为输入的数值都是正数、足够小的数等等。要显式地检测这些条件。 一个设计良好的苗数应该对所有可能性的输入值都能够正确地执行。要确保所有的 情况都考虑到了并且不会产生错误的输出(比如溢出)
23、。预防性检测对象int findindcx(list<string> list, string targct) if (list = null | target = null) throw new nullpointerexceptiono ;不要认为对象参数不会为空(null)o要显式地检测这个条件。预防性检测数组索引void frob(byte b, int index) if (b = null)throw new nullpointerexception();if (index < 0 | index >= b.length)throw new indexout
24、ofboundsexception();不要认为所以给的数组索引不会越界。要显式地检测它。预防性检测数组区间void frob(byte b, int off, int len) if (b = null)throw new nullpointerexception();if (off < 0 | off > b.length| len < 0 | | b. length - off < len) throw new indexoutofboundsexception();不要认为所给的数组区间(比如,从off开始,读取len个元素)是不会越界。要显 式地检测它。填充数
25、组元素使用循环:/ fill each element of array 'a' with 123 byte a =(.);for (int i = 0; i < a length; i+)ai = 123;(优先)使用标准库的方法:arrays, fill (a, (byte) 123);参考:java.util.arrays.fill(tj, t)o 参考:java.util.arrays.fill(t, int, int, t)o复制一个范围内的数组元素使用循环:/ copy 8 elements from array 'a' starting at
26、 offset 3 / to array ,b, starting at offsct 6,/ assuming ' a" and ' b" are distinct arrays byte a =(.);byte b =(.);for (int i 二 0; i < 8; i+)b6 + i = a3 + i;(优先)使用标准库的方法:system, arraycopy (a, 3, b, 6, 8); 参考:javaangsystcm.arraycopy(objcct, int, object, int, int)。调整数组大小使用循环(扩大规模):/ make array 'a' larger to newlenbyte a =(.);byte b = new bytenewlen;for (int i = 0; i < a. length; i+)/ goes up to length of abi二 ai;a = b;使用循环(减小规模):/ make array 'a' smaller to newlenbyte a 二(.);b
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 医药销售拜访技巧培训课件
- 环境监测技术练习测试题附答案
- 世界经济的区域集团化课件
- 《工法样板策划》课件
- 公司股份制改革合同文本解析
- Unit 3 Where did you go?(说课稿)-2023-2024学年人教PEP版英语六年级下册
- 初中生励志电影观后感当幸福来敲门
- 阿甘正传的成长故事解读与感悟
- 企业项目发展调研报告分析
- 合同股权担保合同
- 2023湖南株洲市茶陵县茶陵湘剧保护传承中心招聘5人高频考点题库(共500题含答案解析)模拟练习试卷
- 400字作文稿纸(方格)A4打印模板
- 不领证的夫妻离婚协议书
- 华为BEM战略解码体系完整版
- Python商务数据分析与实战PPT完整全套教学课件
- 利用“自然笔记”提高小学生科学素养获奖科研报告
- 焓湿图的应用实例
- 江西省上饶市高三一模理综化学试题附参考答案
- 《是谁觉醒了中国》
- 23-张方红-IVF的治疗流程及护理
- 初一经典、励志主题班会PPT(共63张PPT)
评论
0/150
提交评论