Q:Java集合框架都有哪些最佳实践呢?
A:根据实际的使用情况选择合适的数据结构,例如固定大小的还是需要增加大小的,有重复元素的还是没有的,需要保持有序还是不需要,遍历是正向的还是双向的,插入是在末尾的还是任意位置的,更多的插入还是更多的读取,是否需要并行访问,是否允许修改,元素类型是相同的还是不同的,等等。另外,还需要尽早考虑多线程,原子性,内存使用量以及性能等因素。
不要假设你的集合里元素的数量一直会保持较小,它也有可能随着时间增长。所以,你的集合最好能够给定一个合适的大小。
针对接口编程优于针对实现编程。例如,可能在某些情况下,LinkedList是最佳的选择,但是后来ArrayList可能因为性能的原因变得更加合适
ArrayList list =
new
ArrayList(
100
);
好的方式:
// program to www.bjfp66.com interface so that the implementation canchange
List list =
new
ArrayList(
100
);
List list2 =
new
LinkedList(
100
);
List emptyList = Collections.emptyList( );
Set emptySet = Collections.emptySet( );
在取得列表的时候,如果返回的结果是空的话,最好返回一个长度为0的集合或者数组,而不要返回null。因为,返回null的话可能能会导致程序错误。调用你的方法的开发人员可能会忘记对返回为null的情况进行处理。
封装好集合:一般来说,集合都是不可变的对象。所以尽量不要把集合的成员变量暴露给调用者。因为他们的操作一般都不会进行必要的校验。
注:这些Java面试题和答案都是从我的书《Core Java Career Essentials》里提取出来的。
英文原文:java-success,编译:ImportNew
译文地址:
【如需转载,请在正文中标注并保留原文链接、译文链接和译者等信息,谢谢合作!】