It took a few hours summarizes some of the error-prone Java knowledge!

This article has been included since JavaGuide (61K + Star! [+ Java learning interview guidelines would cover the majority of Java programmers need to master the core knowledge. Welcome to Star! Welcome harassment!)

Original Address: https: //javaguide.cn/2019/08/20/java/java%E5%9F%BA%E7%A1%80/Java%E7%96%91%E9%9A%BE%E7%82 % B9 /

1. Basic

1.1. Proper use equals method

equals method of Object readily shorting pointer exception, should be used with a constant or a value determined object equals to call.

for example:

// 不能使用一个值为null的引用类型变量来调用非静态方法,否则会抛出异常
String str = null;
if (str.equals("SnailClimb")) {
  ...
} else {
  ..
}复制代码

Run the above procedure will throw a null pointer exception, but we judge the condition of the second line of the statement was changed following the case, it will not throw a null pointer exception, else statement block is executed. :

"SnailClimb".equals(str);// false 复制代码

But more is recommended java.util.Objects#equals(JDK7 introduced tools).

Objects.equals(null,"SnailClimb");// false复制代码

We look at the java.util.Objects#equalssource code to know why.

public static boolean equals(Object a, Object b) {
        // 可以避免空指针异常。如果a==null的话此时a.equals(b)就不会得到执行,避免出现空指针异常。
        return (a == b) || (a != null && a.equals(b));
    }复制代码

note:

Reference: the Java equals method in the cause null-pointer exceptions and solutions

  • Each primitive type has the same default value, such as int default value is 0, boolean default value is false, null is the default value for any reference type, strictly speaking, is not the default for all type Object.
  • Or may be used ==! = Null value comparison operation, but can not use the algorithms or other logical operations. In Java null == nullwill return true.
  • You can not use a null value of a reference type variable to call non-static methods, otherwise it will throw an exception

Comparison 1.2. Packaging integer value

All packaging Integer Comparison object value equals method must be used.

Look at the following example:

Integer x = 3;
Integer y = 3;
System.out.println(x == y);// true
Integer a = new Integer(3);
Integer b = new Integer(3);
System.out.println(a == b);//false
System.out.println(a.equals(b));//true复制代码

When creating an Integer object using automatic packing mode, when the value at -128 ~ 127, Integer cached objects will be created, when the value again next time, corresponding to the Integer object taken directly from the cache. Therefore, the code above, x and y refer to the same Integer object.

Note: If Alibaba p3c plug-in installed on your IDE (IDEA / Eclipse), this plugin if you use == detected, then will prompt an error, it is recommended to install a plug-in, very good.

1.3. BigDecimal

1.3.1. BigDecimal usefulness

"Ali Baba Java Development Manual" is mentioned: equivalence between the floating-point judgment, the basic data types can not be used == to compare, packaging data types can not be judged by equals. Specific principles and coding float about here is not to mention, we direct the following examples:

float a = 1.0f - 0.9f;
float b = 0.9f - 0.8f;
System.out.println(a);// 0.100000024
System.out.println(b);// 0.099999964
System.out.println(a == b);// false复制代码

We have a basic knowledge of mathematics clearly know that the output is not what we want ( loss of precision ), how do we solve this problem? A very common method is: using BigDecimal used to define the floating point value, then the floating-point arithmetic operation.

BigDecimal a = new BigDecimal("1.0");
BigDecimal b = new BigDecimal("0.9");
BigDecimal c = new BigDecimal("0.8");
BigDecimal x = a.subtract(b);// 0.1
BigDecimal y = b.subtract(c);// 0.1
System.out.println(x.equals(y));// true 复制代码

1.3.2. Compare the size of BigDecimal

a.compareTo(b) : -1 to indicate less than, equal to 0 indicates, that is greater than 1.

BigDecimal a = new BigDecimal("1.0");
BigDecimal b = new BigDecimal("0.9");
System.out.println(a.compareTo(b));// 1复制代码

1.3.3. BigDecimal reserved several decimal places

By setScaleretains several decimal places and ways to set retention rules. There are quite a variety, no record retention rules, IDEA will be prompted.

BigDecimal m = new BigDecimal("1.255433");
BigDecimal n = m.setScale(3,BigDecimal.ROUND_HALF_DOWN);
System.out.println(n);// 1.255复制代码

1.3.4. BigDecimal precautions for use

Note: we use BigDecimal, in order to prevent loss of precision, it is recommended to use the BigDecimal (String) constructor to create the object. "Ali Baba Java Development Manual," this part of the content is also mentioned as shown below.

"Ali Baba Java Development Manual" describing this part of BigDecimal

1.3.5 Summary

BigDecimal is mainly used to operate (large) float, BigInteger primarily used to operate large integer (long type over).

BigDecimal to achieve using BigInteger, the difference is added to the concept BigDecimal decimal places

1.4. Basic data types and data types of packaging using standard

Reference: "Ali Baba Java Development Manual"

  • [Mandatory] All POJO class property must use packaging data type.
  • [Force] RPC parameter and return value data type packaging must be used.
  • [Recommended] all local variables using the basic data types.

For example, if we customized a Student class, which has a property that achievement score, if Integer instead of int definitions, exam, students may not test the value is null, it may test, but exam 0, value is 0, the expression of these two states is obviously not the same.

Description : POJO class property is not the initial alert the user when needed, you must explicitly assign their own, NPE any questions or warehousing inspection, by the user to be guaranteed.

Positive examples : database results may be null, because the automatic unpacking, with basic data types have to receive NPE risk.

Counterexample : the total turnover of ups and downs such as display cases, that is plus or minus x%, x is the basic data types, called RPC service when the call is unsuccessful, the returned value is the default page displayed as 0%, which is unreasonable, It should be displayed as the scribe line. So Packaging data type null value can represent additional information, such as: remote call fails, quit unexpectedly.

2. collection

2.1. Arrays.asList () Guide

Recent Arrays.asList()encountered some pit, then in line to see this article: the Java Array to List Examples feeling pretty good, but not particularly comprehensive. So, himself a brief summary for a small piece of knowledge.

2.1.1 Introduction

Arrays.asList()In peacetime development is still relatively common, we can use it to convert an array to a List collection.

String[] myArray = { "Apple", "Banana", "Orange" }; 
List<String> myList = Arrays.asList(myArray);
//上面两个语句等价于下面一条语句
List<String> myList = Arrays.asList("Apple","Banana", "Orange");复制代码

JDK source code for this method of explanation:

/**
 *返回由指定数组支持的固定大小的列表。此方法作为基于数组和基于集合的API之间的桥梁,与           Collection.toArray()结合使用。返回的List是可序列化并实现RandomAccess接口。
 */ 
public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}复制代码

2.1.2. "Alibaba Java Development Manual" for its description

Arrays.asList()After converting the array is a collection, but it is still the underlying array, "Ali Baba Java Development Manual" For this method has the following description:

Alibaba Java developers hand -Arrays.asList () methodMethods .png)

2.1.3. Precautions when using summary

The array must be passed an array of objects, rather than primitive types.

Arrays.asList()Is a generic method, the object must be passed in an array of objects.

int[] myArray = { 1, 2, 3 };
List myList = Arrays.asList(myArray);
System.out.println(myList.size());//1
System.out.println(myList.get(0));//数组地址值
System.out.println(myList.get(1));//报错:ArrayIndexOutOfBoundsException
int [] array=(int[]) myList.get(0);
System.out.println(array[0]);//1复制代码

When passing a native data type of the array, Arrays.asList()the argument is not truly element in the array, but the array object itself! At this point the only element List is this array, which explains the above code.

We use an array of packaging types can solve this problem.

Integer[] myArray = { 1, 2, 3 };复制代码

Using a modified method of collection: , , throws an exception.add()remove()clear()

List myList = Arrays.asList(1, 2, 3);
myList.add(4);//运行时报错:UnsupportedOperationException
myList.remove(1);//运行时报错:UnsupportedOperationException
myList.clear();//运行时报错:UnsupportedOperationException复制代码

Arrays.asList()The method is not returned java.util.ArrayList, but java.util.Arraysan inner class, this class does not implement internal modification methods for the collection or did not override these methods.

List myList = Arrays.asList(1, 2, 3);
System.out.println(myList.getClass());//class java.util.Arrays$ArrayList复制代码

Below is java.util.Arrays$ArrayLista simple source code, we can see that the methods of this class to override what.

  private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess, java.io.Serializable
    {
        ...

        @Override
        public E get(int index) {
          ...
        }

        @Override
        public E set(int index, E element) {
          ...
        }

        @Override
        public int indexOf(Object o) {
          ...
        }

        @Override
        public boolean contains(Object o) {
           ...
        }

        @Override
        public void forEach(Consumer<? super E> action) {
          ...
        }

        @Override
        public void replaceAll(UnaryOperator<E> operator) {
          ...
        }

        @Override
        public void sort(Comparator<? super E> c) {
          ...
        }
    }复制代码

Let's look at java.util.AbstractListthe remove()method, so that we understand why throws UnsupportedOperationException.

public E remove(int index) {
    throw new UnsupportedOperationException();
}复制代码

2.1.4. How to properly convert the array to ArrayList?

Stack Overflow: https: //dwz.cn/vcBkTiTW

1. achieve yourself (for educational purposes)

//JDK1.5+
static <T> List<T> arrayToList(final T[] array) {
  final List<T> l = new ArrayList<T>(array.length);

  for (final T s : array) {
    l.add(s);
  }
  return (l);
}复制代码

Integer [] myArray = { 1, 2, 3 };
System.out.println(arrayToList(myArray).getClass());//class java.util.ArrayList复制代码

2. The easiest way (recommended)

List list = new ArrayList<>(Arrays.asList("a", "b", "c"))复制代码

3. Use Java8 of Stream (recommended)

Integer [] myArray = { 1, 2, 3 };
List myList = Arrays.stream(myArray).collect(Collectors.toList());
//基本类型也可以实现转换(依赖boxed的装箱操作)
int [] myArray2 = { 1, 2, 3 };
List myList = Arrays.stream(myArray2).boxed().collect(Collectors.toList());复制代码

4. Guava (recommended)

For immutable set, you can use the ImmutableListclass and of()the copyOf()factory method :( parameter can be null)

List<String> il = ImmutableList.of("string", "elements");  // from varargs
List<String> il = ImmutableList.copyOf(aStringArray);      // from array复制代码

For variable collection, you can use the Listsclass and its newArrayList()factory method:

List<String> l1 = Lists.newArrayList(anotherListOrCollection);    // from collection
List<String> l2 = Lists.newArrayList(aStringArray);               // from array
List<String> l3 = Lists.newArrayList("or", "string", "elements"); // from varargs复制代码

5. Use Apache Commons Collections

List<String> list = new ArrayList<String>();
CollectionUtils.addAll(list, str);复制代码

2.2. Collection.toArray () method used pit & How to Reverse the array

This method is a generic method: If the method does not pass any parameters, then returns the type of array. T[] toArray(T[] a); toArrayObject

String [] s= new String[]{
    "dog", "lazy", "a", "over", "jumps", "fox", "brown", "quick", "A"
};
List<String> list = Arrays.asList(s);
Collections.reverse(list);
s=list.toArray(new String[0]);//没有指定类型的话会报错复制代码

Because of JVM optimization, new String[0]as a Collection.toArray()method parameter now better, new String[0]that acts as a template that specifies the type of the returned array, 0 is to save space, because it is only to illustrate the type of return. See:

2.3. Remove / add elements not to be in operation in the foreach loop

If you want to removeoperate, you can call the iterator's remove remove methods rather than a collection of classes. If you modify the list because after the iterator is created from the structure at any time, in any way except through the iterator's own remove/addmethod, the iterator will throw a ConcurrentModificationException, which is produced under the single-threaded state fail-fast mechanism .

fail-fast mechanism : when multiple threads for fail-fast set of changes, may throw ConcurrentModificationException, will happen under the single-threaded, already mentioned above.

java.utilAll packets are collections following fail-fast, and java.util.concurrentpackets are all of the following classes of fail-safe.

remove / add operations not carried out in the elements in the foreach loop

Open source projects recommended

On the recommendation of other open source projects:

  1. JavaGuide : Java learning [+] Interview Guide covers a majority of Java programmers need to master the core knowledge.
  2. Guide-springboot : suitable for beginners as well as experienced developers access to the Spring Boot tutorial (spare time maintenance, maintenance welcome together).
  3. Advancement-Programmer : I think the technical staff should have some good habits!
  4. -Security-jwt-the Spring Guide : Getting started from zero! Spring Security With JWT (including verification authority) a rear end part of the code.

the public

My public number

Guess you like

Origin juejin.im/post/5dd3c70d5188251198588611