明代王阳明先生在《传习录》谈为学之道时说:
私欲日生,如地上尘,一日不扫,便又有一层。着实用功,便见道无终穷,愈探愈深,必使精白无一毫不彻方可。
Map<
String,
String> map = ...;
for (
String key : map.keySet()) {
String value = map.
get(key);
...
}
Map<
String,
String> map = ...;
for (
Map.Entry<
String,
String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
...
}
if (collection.size() ==
0) {
...
}
if (collection.isEmpty()) {
...
}
List<String>
list =
new ArrayList<>();
list.add(
"Hello");
list.add(
"World");
if (
list.containsAll(
list)) {
// 无意义,总是返回true
...
}
list.removeAll(
list);
// 性能差, 直接使用clear()
int[] arr =
new
int[]{
1,
2,
3};
List<Integer>
list =
new ArrayList<>();
for (
int i : arr) {
list.add(i);
}
int[] arr =
new
int[]{
1,
2,
3};
List<Integer>
list =
new ArrayList<>(arr.length);
for (
int i : arr) {
list.add(i);
}
String s =
"";
for (
int i =
0; i <
10; i++) {
s += i;
}
String a =
"a";
String b =
"b";
String c =
"c";
String s = a + b + c;
// 没问题,java编译器会进行优化
StringBuilder sb =
new StringBuilder();
for (
int i =
0; i <
10; i++) {
sb.append(i);
// 循环中,java编译器无法进行优化,所以要手动使用StringBuilder
}
// 调用别人的服务获取到list
List<Integer>
list = otherService.getList();
if (
list
instanceof RandomAccess) {
// 内部数组实现,可以随机访问
System.out.println(
list.get(
list.size() -
1));
}
else {
// 内部可能是链表实现,随机访问效率低
}
频繁调用 Collection.contains 方法请使用 Set
ArrayList<Integer>
list = otherService.getList();
for (
int i =
0; i <= Integer.MAX_VALUE; i++) {
// 时间复杂度O(n)
list.contains(i);
}
正例:
ArrayList<Integer> list = otherService.getList();
Set<Integer> set = new HashSet(list);
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
// 时间复杂度O(1)
set.contains(i);
}
long value = 1l;
long max = Math.max(1L, 5);
正例:
long
value =
1L;
long max = Math.max(
1L,
5L);
for (int i =
0; i <
100; i++){
...
}
if (a ==
100) {
...
}
private
static
final
int MAX_COUNT =
100;
for (
int i =
0; i < MAX_COUNT; i++){
...
}
if (count == MAX_COUNT) {
...
}
private
static
Map<
String, Integer> map =
new HashMap<
String, Integer>() {
{
put(
"a",
1);
put(
"b",
2);
}
};
private
static
List<
String> list =
new ArrayList<
String>() {
{
add(
"a");
add(
"b");
}
};
private
static Map<String, Integer>
map =
new HashMap<>();
static {
map.put(
"a",
1);
map.put(
"b",
2);
};
private
static List<String>
list =
new ArrayList<>();
static {
list.add(
"a");
list.add(
"b");
};
private void handle(String fileName) {
BufferedReader reader = null;
try {
String line;
reader = new BufferedReader(new FileReader(fileName));
while ((line = reader.readLine()) != null) {
...
}
} catch (Exception e) {
...
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
...
}
}
}
}
正例:
private void handle(String fileName) {
try (BufferedReader reader =
new BufferedReader(
new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) !=
null) {
...
}
}
catch (Exception e) {
...
}
}
public
class DoubleDemo1 {
private
int unusedField =
100;
private void unusedMethod() {
...
}
public int sum(int a, int b) {
return a + b;
}
}
public class DoubleDemo1 {
public int sum(int a, int b) {
return a + b;
}
}
public int sum(int a, int b) {
int c =
100;
return a + b;
}
public int sum(int a, int b) {
return a + b;
}
删除未使用的方法参数
未使用的方法参数具有误导性,删除未使用的方法参数,使代码更简洁更易维护。但是,由于重写方法是基于父类或接口的方法定义,即便有未使用的方法参数,也是不能删除的。
public int sum(int a, int b, int c) {
return a + b;
}
public int sum(int a, int b) {
return a + b;
}
return (x);
return (x +
2);
int x = (y *
3) +
1;
int m = (n *
4 +
2);
return x;
return x +
2;
int x = y *
3 +
1;
int m = n *
4 +
2;
public
class MathUtils {
public
static
final
double PI =
3.1415926D;
public static int sum(int a, int b) {
return a + b;
}
}
public
class MathUtils {
public
static
final
double PI =
3.1415926D;
private MathUtils() {}
public static int sum(int a, int b) {
return a + b;
}
}
private static String readFile(String fileName) throws IOException {
try (BufferedReader reader =
new BufferedReader(
new FileReader(fileName))) {
String line;
StringBuilder builder =
new StringBuilder();
while ((line = reader.readLine()) !=
null) {
builder.append(line);
}
return builder.toString();
}
catch (Exception e) {
throw e;
}
}
private static String readFile(String fileName) throws IOException {
try (BufferedReader reader =
new BufferedReader(
new FileReader(fileName))) {
String line;
StringBuilder builder =
new StringBuilder();
while ((line = reader.readLine()) !=
null) {
builder.append(line);
}
return builder.toString();
}
}
public
class User {
public
static
final String CONST_NAME =
"name";
...
}
User user =
new User();
String nameKey = user.CONST_NAME;
public
class User {
public
static
final String CONST_NAME =
"name";
...
}
String nameKey = User.CONST_NAME;
public String getUserName(User user) {
try {
return user.getName();
}
catch (NullPointerException e) {
return
null;
}
}
public String getUserName(User user) {
if (Objects.isNull(user)) {
return
null;
}
return user.getName();
}
使用String.valueOf(value)代替""+value
当要把其它对象或类型转化为字符串时,使用 String.valueOf(value) 比""+value 的效率更高。
int i =
1;
String s =
"" + i;
int i =
1;
String s =
String.valueOf(i);
正例:
/**
* 保存
*
* @deprecated 此方法效率较低,请使用{@link newSave()}方法替换它
*/
@Deprecated
public void save(){
// do something
}
BigDecimal
value =
new BigDecimal(
0.1D);
// 0.100000000000000005551115...
BigDecimal
value = BigDecimal.valueOf(
0.1D);;
// 0.1
public
static Result[] getResults() {
return
null;
}
public
static
List<Result> getResultList() {
return
null;
}
public
static
Map<
String, Result> getResultMap() {
return
null;
}
public
static
void main(
String[] args) {
Result[] results = getResults();
if (results !=
null) {
for (Result result : results) {
...
}
}
List<Result> resultList = getResultList();
if (resultList !=
null) {
for (Result result : resultList) {
...
}
}
Map<
String, Result> resultMap = getResultMap();
if (resultMap !=
null) {
for (
Map.Entry<
String, Result> resultEntry : resultMap) {
...
}
}
}
public
static Result[] getResults() {
return
new Result[
0];
}
public
static
List<Result> getResultList() {
return Collections.emptyList();
}
public
static
Map<
String, Result> getResultMap() {
return Collections.emptyMap();
}
public
static
void main(
String[] args) {
Result[] results = getResults();
for (Result result : results) {
...
}
List<Result> resultList = getResultList();
for (Result result : resultList) {
...
}
Map<
String, Result> resultMap = getResultMap();
for (
Map.Entry<
String, Result> resultEntry : resultMap) {
...
}
}
public void isFinished(OrderStatus status) {
return status.
equals(OrderStatus.FINISHED);
// 可能抛空指针异常
}
public void isFinished(OrderStatus status) {
return OrderStatus.FINISHED.
equals(status);
}
public void isFinished(OrderStatus status) {
return Objects.
equals(status, OrderStatus.FINISHED);
}
public
enum UserStatus {
DISABLED(
0,
"禁用"),
ENABLED(
1,
"启用");
public
int
value;
private String description;
private UserStatus(int value, String description) {
this.
value =
value;
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
正例:
public
enum UserStatus {
DISABLED(
0,
"禁用"),
ENABLED(
1,
"启用");
private final
int
value;
private final String description;
private UserStatus(int value, String description) {
this.
value =
value;
this.description = description;
}
public int getValue() {
return
value;
}
public String getDescription() {
return description;
}
}
"a.ab.abc".
split(
".");
// 结果为[]
"a|ab|abc".
split(
"|");
// 结果为[
"a",
"|",
"a",
"b",
"|",
"a",
"b",
"c"]
正例:
"a.ab.abc".split("\\."); // 结果为["a", "ab", "abc"]
"a|ab|abc".split("\\|"); // 结果为["a", "ab", "abc"]
这篇文章,可以说是从事 Java 开发的经验总结,分享出来以供大家参考。希望能帮大家避免踩坑,让代码更加高效优雅。