Top 10 Mistakes Java Developers Make

本文总结了Java开发者常犯的十大错误,包括数组转ArrayList的不当方式、检查数组是否包含值的低效做法、循环中移除元素导致的问题、Hashtable与HashMap的误用、集合原始类型的危险使用等,为Java程序员提供了宝贵的改进建议。

http://www.programcreek.com/2014/05/top-10-mistakes-java-developers-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 for java.util.Arrays.ArrayList.


#2. Check If an Array Contains a Value


Developers often do:


Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);
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){
if(s.equals(targetValue))
return true;
}
return false;
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"));
for (int i = 0; i < list.size(); i++) {
list.remove(i);
}
System.out.println(list);
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"));
 
for (String s : list) {
if (s.equals("a"))
list.remove(s);
}
It will throw out ConcurrentModificationException.


Instead the following is OK:


ArrayList<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c", "d"));
Iterator<String> iter = list.iterator();
while (iter.hasNext()) {
String s = iter.next();
 
if (s.equals("a")) {
iter.remove();
}
}
.next() must be called before .remove(). In the foreach loop, compiler will make the .next() called after the operation of removing element, which caused the ConcurrentModificationException. You may want to take a look at the source code of ArrayList.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 that Hashtable 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, Set is 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){
list.add(o);
}
public static void main(String[] args){
List<String> list = new ArrayList<String>();
add(list, 10);
String s = list.get(0);
}
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 use ArrayList, 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="";
for(String s: arr){
result = result + s;
}
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)


Why String is Immutable?


#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(){
    System.out.println("Super");
}
, or 2) remove the self-defined Super constructor, or 3) add super(value) to sub constructors.


Constructor of Super and Sub


#10. "" or Constructor?


String can be created by two ways:


//1. use double quotes
String x = "abc";
//2. use constructor
String y = new String("abc");
What is the difference?


The following examples can provide a quick answer:


String a = "abcd";
String b = "abcd";
System.out.println(a == b);  // True
System.out.println(a.equals(b)); // True
 
String c = new String("abcd");
String d = new String("abcd");
System.out.println(c == d);  // False
System.out.println(c.equals(d)); // True
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.
内容概要:本文介绍了一个基于多传感器融合的定位系统设计方案,采用GPS、里程计和电子罗盘作为定位传感器,利用扩展卡尔曼滤波(EKF)算法对多源传感器数据进行融合处理,最终输出目标的滤波后位置信息,并提供了完整的Matlab代码实现。该方法有效提升了定位精度与稳定性,尤其适用于存在单一传感器误差或信号丢失的复杂环境,如自动驾驶、移动采用GPS、里程计和电子罗盘作为定位传感器,EKF作为多传感器的融合算法,最终输出目标的滤波位置(Matlab代码实现)机器人导航等领域。文中详细阐述了各传感器的数据建模方式、状态转移与观测方程构建,以及EKF算法的具体实现步骤,具有较强的工程实践价值。; 适合人群:具备一定Matlab编程基础,熟悉传感器原理和滤波算法的高校研究生、科研人员及从事自动驾驶、机器人导航等相关领域的工程技术人员。; 使用场景及目标:①学习和掌握多传感器融合的基本理论与实现方法;②应用于移动机器人、无人车、无人机等系统的高精度定位与导航开发;③作为EKF算法在实际工程中应用的教学案例或项目参考; 阅读建议:建议读者结合Matlab代码逐行理解算法实现过程,重点关注状态预测与观测更新模块的设计逻辑,可尝试引入真实传感器数据或仿真噪声环境以验证算法鲁棒性,并进一步拓展至UKF、PF等更高级滤波算法的研究与对比。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值