Usage and analysis of String

Posted by sam2004 on Wed, 05 Jan 2022 19:48:56 +0100

String - (not null, "+", value comparison, String.format())

Sting is the most frequently encountered type in work, so no matter what business environment, understanding the usage of String and skillfully using String type can solve many problems.

1, Methods to judge whether a String is not empty include:

  1. str != null; (most used)

    Advantages: the code is intuitive and easy to understand

    Disadvantages: low efficiency

  2. " ". equals(str); (minimum use)

  3. str.length() != 0;

    Highest efficiency

2, Principle and efficiency of string connection realized by "+" connector:

In some environments, such as the automatic generation of serial numbers of e-tickets, uuid can not meet our orderly and unique business needs, so we often need to splice and accumulate strings, so I became interested in the "+" character.

//The following two are equivalent
String a = "";
String i = "";
a = i + "";
a = String.valueOf(i);
//After entering the bottom layer, you can find that it is the default toString method.
 public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }
--------------------------------------------------------
//The following two are also equivalent
a = "123" + i;
a = new StringBuilder("123").append(i).toString();
//You can find it when you enter the bottom layer
  @Override
    public StringBuilder append(Object obj) {
        return append(String.valueOf(obj));
    }
//When Java uses "+" to connect string objects, it creates a StringBuilder() object and calls the append() method to splice the data. Finally, the toString() method is used to return the spliced string.
--------------------------------------------------------
String a = "123";
for (int i=0; i<10000; i++) {
    a += "123";
   //a = (new StringBuilder()).append(a).append("123").toString();  Equivalent to previous line
}
//It can be found that each accumulation will create a new StringBuilder object, which will fill a lot of space in the heap memory and slow down the efficiency.

3, String type value comparison "= =" VS "equals()":

"Double equals" determines the address value of heap memory, and the equals() method determines the content.

equals() is usually used most and is relatively safe. If the result of equals() is true, their hashCode () is the same. Therefore, use equals() instead!

java regulations

If the hashcodes () of two objects are equal, their equals() are not necessarily equal.
If the equals() of two objects are equal, their hashCode() must be equal.

When overriding the equals() method, be sure to override the hashCode() method

Here are small partners interested in the algorithm

static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

// key.hashCode() ^ (key.hashCode() >>> 16)
//This ingenious perturbation algorithm
//==============================Source hash Code==========================
      final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

4, String Format() uses:

Here is a working example: the requirement is to generate a unique electronic serial number, which is generated from the beginning of a letter + date + 7 digits: my scheme is to generate a maximum value from the database each time for the accumulation of the current day, and re count from 0 if it is not the current day (similar to the condition counter)

public synchronized int generateSerial () {
    //This is the query database. If there is the electronic serial number of the most row in the database, take it out for disassembly and extract the last 7 digits
    String findnewszph = sewageWaterFeeReceiveGDDao.findnewszph();
        if (findnewszph != null) {
            //Date of withdrawal: 20170607
            String sqlDate = findnewszph.substring(8, 14);
            //Take out the last seven digits eg: 0000001
            String sevenNumber = findnewszph.substring(15);
            //Cutting 0 operation
            int num = Integer.parseInt(sevenNumber);
            SimpleDateFormat df = new SimpleDateFormat("yyMMdd");//Format date
           	//Get the date of the latest row
            String format = df.format(new Date());
            //Judge whether it's today
            if (sqlDate.equals(format)) {
                num++;
            } else {
                num = 0;
            }
            return num;
        }
        return 0;
}

public String seqNo(){
    String A ="";
    String seqno = "GD04";
    SimpleDateFormat df = new SimpleDateFormat("yyMMdd");//Format date
    String seqno1 = seqno + "01" + df.format(new Date());
    //Query the last item in the database. If the date obtained is not today's date, reset the last 7 bits from 0
    A = seqno1 + String.format("%07d",generateSerial());
    //  System.out.println("seqNo message serial number is:" + A)// Verify that the function is correct
    return A;
}

Topics: Java string