Top 10 Mistakes Java Developers Make--reference
This list summarizes the top 10 mistakes that Java developers frequently make.
#1. Convert Array to ArrayList
To convert an array to an ArrayList, developers often do this:
List<String> list = Arrays.asList(arr); |
Arrays.asList() will return an ArrayList which is a private static class inside Arrays, it is not the java.util.ArrayList class. The java.util.Arrays.ArrayList class has set(),get(), contains() methods, but does not have any methods for adding elements, so its size is fixed. To create a real ArrayList, you should do:
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(arr)); |
The constructor of ArrayList can accept a Collection type, which is also a super type forjava.util.Arrays.ArrayList.
#2. Check If an Array Contains a Value
Developers often do:
Set<String> set = new HashSet<String>(Arrays.asList(arr)); |
The code works, but there is no need to convert a list to set first. Converting a list to a set requires extra time. It can as simple as:
Arrays.asList(arr).contains(targetValue); |
or
for(String s: arr){
|
The first one is more readable than the second one.
#3. Remove an Element from a List Inside a Loop
Consider the following code which removes elements during iteration:
ArrayList<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c", "d"));
|
The output is:
[b, d]
There is a serious problem in this method. When an element is removed, the size of the list shrinks and the index changes. So if you want to delete multiple elements inside a loop by using the index, that will not work properly.
You may know that using iterator is the right way to delete elements inside loops, and you know foreach loop in Java works like an iterator, but actually it is not. Consider the following code:
ArrayList<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c", "d"));
|
It will throw out ConcurrentModificationException.
Instead the following is OK:
ArrayList<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c", "d"));
|
.next() must be called before .remove(). In the foreach loop, compiler will make the .next()called after the operation of removing element, which caused theConcurrentModificationException. You may want to take a look at the source code ofArrayList.iterator().
#4. Hashtable vs HashMap
By conventions in algorithm, Hashtable is the name of the data structure. But in Java, the data structure's name is HashMap. One of the key differences between Hashtable and HashMap is thatHashtable is synchronized. So very often you don't need Hashtable, instead HashMap should be used.
HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap
Top 10 questions about Map
#5. Use Raw Type of Collection
In Java, raw type and unbounded wildcard type are easy to mixed together. Take Set for example, Setis raw type, while Set<?> is unbounded wildcard type.
Consider the following code which uses a raw type List as a parameter:
public static void add(List list, Object o){
|
This code will throw an exception:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at ...
Using raw type collection is dangerous as the raw type collections skip the generic type checking and not safe. There are huge differences between Set, Set<?>, and Set<Object>. Check out
Raw type vs. Unbounded wildcard and Type Erasure.
#6. Access Level
Very often developers use public for class field. It is easy to get the field value by directly referencing, but this is a very bad design. The rule of thumb is giving access level for members as low as possible.
public, default, protected, and private
#7. ArrayList vs. LinkedList
When developers do not know the difference between ArrayList and LinkedList, they often useArrayList, because it looks familiar. However, there is a huge performance difference between them. In brief, LinkedList should be preferred if there are a large number of add/remove operations and there are not a lot of random access operations. Check out ArrayList vs. LinkedList to get more information about their performance if this is new to you.
#8. Mutable vs. Immutable
Immutable objects have many advantages such simplicity, safety, etc. But it requires a separate object for each distinct value, and too many objects might cause high cost of garbage collection. There should be a balance when choosing between mutable and immutable.
In general, mutable objects are used to avoid producing too many intermediate objects. One classic example is concatenating a large number of strings. If you use an immutable string, you would produce a lot of objects that are eligible for garbage collection immediately. This wastes time and energy on the CPU, using a mutable object the right solution (e.g. StringBuilder).
String result=""; |
There are other situations when mutable objects are desirable. For example passing mutable objects into methods lets you collect multiple results without jumping through too many syntactic hoops. Another example is sorting and filtering: of course, you could make a method that takes the original collection, and returns a sorted one, but that would become extremely wasteful for larger collections. (From dasblinkenlight's answer on Stack Overflow)
#9. Constructor of Super and Sub

This compilation error occurs because the default super constructor is undefined. In Java, if a class does not define a constructor, compiler will insert a default no-argument constructor for the class by default. If a constructor is defined in Super class, in this case Super(String s), compiler will not insert the default no-argument constructor. This is the situation for the Super class above.
The constructors of the Sub class, either with-argument or no-argument, will call the no-argument Super constructor. Since compiler tries to insert super() to the 2 constructors in the Sub class, but the Super's default constructor is not defined, compiler reports the error message.
To fix this problem, simply 1) add a Super() constructor to the Super class like
public Super(){
|
, or 2) remove the self-defined Super constructor, or 3) add super(value) to sub constructors.
#10. "" or Constructor?
String can be created by two ways:
//1. use double quotes |
What is the difference?
The following examples can provide a quick answer:
String a = "abcd"; |
For more details about how they are allocated in memory, check out Create Java String Using ” ” or Constructor?.
Future Work
The list is based on my analysis of a large number of open source projects on GitHub, Stack Overflow questions, and popular Google queries. There is no evaluation to prove that they are precisely the top 10, but definitely they are very common. Please leave your comment, if you don’t agree with any part. I would really appreciate it if you could point out some other mistakes that are more common.
reference from:http://www.programcreek.com/2014/05/top-10-mistakes-java-developers-make/
Top 10 Mistakes Java Developers Make--reference的更多相关文章
- Top 10 Mistakes Java Developers Make(转)
文章列出了Java开发者最常犯的是个错误. 1.将数组转换为ArrayList 为了将数组转换为ArrayList,开发者经常会这样做: ? 1 List<String> list = A ...
- Yet Another 10 Common Mistakes Java Developers Make When Writing SQL (You Won’t BELIEVE the Last One)--reference
(Sorry for that click-bait heading. Couldn’t resist ;-) ) We’re on a mission. To teach you SQL. But ...
- 100 high quality blogs from java developers
This list collects 100 high quality blogs from Java developers from all over the world. Some of thes ...
- 2016年排名Top 100的Java类库——在分析了47,251个依赖之后得出的结论(16年文章)
本文由HollisChuang 翻译自 The Top 100 Java Libraries in 2016 – After Analyzing 47,251 Dependencies . 原作者:H ...
- 2016 年排名 Top 100 的 Java 类库
我们分析了GitHub中47,251个依赖,从中找出了排名前一百的Java类库,让我们看看谁在前面,谁在后面. 我们在漫长的周末的消遣方式就是浏览GitHub并且搜索流行的Java类库.我们决定把其中 ...
- Top 10 Books For Advanced Level Java Developers
Java is one of the most popular programming language nowadays. There are plenty of books for beginne ...
- Top 10 Questions about Java Exceptions--reference
reference from:http://www.programcreek.com/2013/10/top-10-questions-about-java-exceptions/ This arti ...
- Top 10 Methods for Java Arrays
作者:X Wang 出处:http://www.programcreek.com/2013/09/top-10-methods-for-java-arrays/ 转载文章,转载请注明作者和出处 The ...
- Watch out for these 10 common pitfalls of experienced Java developers & architects--转
原文地址:http://zeroturnaround.com/rebellabs/watch-out-for-these-10-common-pitfalls-of-experienced-java- ...
随机推荐
- Hibernate的优缺点
Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库. Hibernate可以应用在任何使用JDB ...
- MapReduce——计算温度最大值 (基于全新2.2.0API)
MapReduce——计算温度最大值 (基于全新2.2.0API) deprecated: Job类的所有Constructors, 新的API用静态方法getInstance(conf)来去的Job ...
- [Hadoop源码解读](六)MapReduce篇之MapTask类
MapTask类继承于Task类,它最主要的方法就是run(),用来执行这个Map任务. run()首先设置一个TaskReporter并启动,然后调用JobConf的getUseNewAPI()判断 ...
- BZOJ_1612_[Usaco2008_Jan]_Cow_Contest_奶牛的比赛_(dfs)
描述 http://www.lydsy.com/JudgeOnline/problem.php?id=1612 \(n\)头奶牛比赛,给出一些胜负情况,问可以确定多少头奶牛的排名. 分析 无论胜负,只 ...
- maven安装步骤
第一步:配置maven环境 maven3 安装: 安装 Maven 之前要求先确定你的 JDK 已经安装配置完成.Maven是 Apache 下的一个项目,目前最新版本是 3.0.4,我用的也是这个. ...
- 查询显示MSSQL表结构 [转]
SELECT 表名 = Case When A.colorder= Then D.name Else '' End, 表说明 = Case When A.colorder= Then isnull(F ...
- 一个赴美的应届毕业生Kevin,在美国做程序员的访谈
作者MUM计算机 转载请注明 在国内IT市场人才日渐饱和且竞争激烈的今天,作为一名代号996的程序猿,你是否也会对赴美工作心生向往呢?作为国内普通院校的应届本科生年薪就能轻松破40万 (人民币), ...
- 使用C#模拟ASP.NET页面中按钮点击
c# 模拟Asp.net页面中的某个按钮的点击,向web服务器发出请求 主要就组织要提交的数据,然后以post方式提交. 假设我们有如下的网页 1 <% @ Page Language = &q ...
- vm虚拟机上安装apache+php+ftp+mysql
我在vm虚拟机上想安装 winxp和linux,然后在linux机上装apache+php+ftp+mysql,以下为我的按装过程: 1:连通虚拟机:两个虚拟机都选Host-Onl,查看主机Virt ...
- HDOJ-ACM1097(JAVA) A hard puzzle
这道题就是HDOJ的1061的变形: 1061 :求n的n次方的个位数 http://www.cnblogs.com/xiezie/p/5596779.html 1097 :求n的m次方的个位数 因此 ...