[Java] Top 100 Java Programming Questions---Basic Grammar Series (3)


别光看,动手敲一下代码,运行一下
虽然敲代码有人苦有人乐在其中,祝你开开心心找到那种写完代码成功无bug的乐趣,或者修改bug成功的那种满足感

11. How to compare strings in java

  • ==Corresponding to pointer equality, that is, whether they are the same object
  • .equals()Corresponding to value equality, that is, logical equality

So if you want to check if two strings are the same value then you should use .equals()the method

// 在java中如何对比(compare)string
public class Test01 {
    
    
    public static void main(String[] args) {
    
    
        // 值是相等的
        boolean result01 = new String("test").equals("test");
        System.out.println("new String(\"test\").equals(\"test\"): "+result01);

        // ... 值相等,但不是同个对象(指向不同的地址空间)
        boolean result02 = new String("test") == "test";
        System.out.println("new String(\"test\") == \"test\": "+ result02);

        // ... 同上
        boolean result03 = new String("test") == new String("test");
        System.out.println("new String(\"test\") == new String(\"test\"): "+result03);

        // 这个返回true,是因为这种写法属于字符串字面量,编译器会维护一个常量池,相同的字面量,都会指向相同的一个对象
        boolean result04 = "test" == "test";
        System.out.println("test == test :" + result04);
    }
}

The output is as follows:

new String("test").equals("test"): true
new String("test") == "test": false
new String("test") == new String("test"): false
test == test :true

Therefore, the comparison of values ​​generally uses the equals method. To compare string literals, you can also use ==

Let's take another example of string literals. In the following code, the first four comparisons return true, and the last one returns false.

	public static final String test1 = "test";
	public static final String test2 = "test";

	@Test
	public void test() {
    
    

		String test3 = "test";
		String test = "test";

		System.out.println(test3.equals(test));
		System.out.println(test3 == test);
		System.out.println(test1.equals(test2));
		System.out.println(test1 == test2);
		System.out.println(test1 == new String("test"));
	}

Additional information

  • If you override the equal method, you should modify the corresponding hashcode method, otherwise the equivalence relationship between the two methods will be violated.
    If two objects are equal (equal), then calling the hashCode() method on the two objects must produce the same integer result, that is:
    equal is true, hashCode must also be true, equal is false, hashCode must also be false
  • If you want to ignore case for comparison, you can use the equalsIgnoreCase() method

12. Map<Key,Value> is sorted based on Value

Method 1: Using TreeMap

You can refer to the following code

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

// Map<Key,Value>基于Value值排序
public class Test02 {
    
    
    // 方法1:使用TreeMap
    public static void main(String[] args) {
    
    
        HashMap<String, Double> map = new HashMap<String, Double>();
        ValueComparator bvc = new ValueComparator(map);
        TreeMap<String, Double> sorted_map = new TreeMap<String, Double>(bvc);
        map.put("A", 99.5);
        map.put("B", 67.4);
        map.put("C", 67.4);
        map.put("D", 67.3);

        System.out.println("unsorted map: " + map);
        sorted_map.putAll(map);
        System.out.println("results: " + sorted_map);
    }
}
package day03;

import java.util.Comparator;
import java.util.Map;

class ValueComparator implements Comparator<String> {
    
    
    Map<String, Double> base;

    public ValueComparator(Map<String, Double> base) {
    
    
        this.base = base;
    }

    // 注意:这个compare比较器施加的顺序与等号不一致。
    public int compare(String a, String b) {
    
    
        if (base.get(a) >= base.get(b)) {
    
    
            return -1;
        } else {
    
    
            return 1;
        }
        // 返回0将合并键
    }
}

Annotation: If you don’t write your own Comparator, treemap will sort by key by default.

Method 2:

First sort through linkedlist, and then put it in LinkedHashMap

import java.util.*;

public class MapUtil {
    
    
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    
    
        List<Map.Entry<K, V>> list =
                new LinkedList<Map.Entry<K, V>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
    
    
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
    
    
                return (o1.getValue()).compareTo(o2.getValue());
            }
        });

        Map<K, V> result = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : list) {
    
    
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }
}

Annotation: If the size of the map is above 100,000, both methods will take hundreds of milliseconds, and the second method will be faster. Otherwise, the first method is faster. If the maps you are dealing with are of sizes below hundreds of thousands, you can use either method.

13. The difference between HashMap and Hashtable

Question
What is the difference between HashMap and Hashtable in Java?
Which one is better for multi-threaded applications?
Answer:
The difference between HashMap and Hashtable, the difference between HashMap and ConcurrentHashMap.
Click the link to see the first point.

14. How to combine two numbers together easily

One line of code for tool class

ArrayUtils.addAll(T[], T...)(Tool classes need to introduce maven dependencies, as mentioned in the previous series)

Code:

import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays;
public class Test03 {
    
    
    public static void main(String[] args) {
    
    
        String[] first = {
    
    "I ", "am ", "the ", "first "};
        String[] second = {
    
    "I ", "am ", "second"};
        String[] both = ArrayUtils.addAll(first, second);
        System.out.println(Arrays.toString(both));
    }
}

Without dependency packages

non-generic

Replace the following Applewith your own class name
. Considering that some novices may not be able to write, post an Apple class. In fact, you only need to write the attributes, getter and setter methods, and toString() method, etc., which can be generated with one click. .
pom.xmlImport lombok dependencies in

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
@Getter@Setter
@AllArgsConstructor
@ToString
public class Apple {
    
    
    private String color;
    private int count;
}

The Apple class can directly paste a lombok annotation to save trouble. The following is the detailed code.

public class Apple {
    
    
    private String color;
    private int count;

    public String getColor() {
    
    
        return color;
    }

    public void setColor(String color) {
    
    
        this.color = color;
    }

    public int getCount() {
    
    
        return count;
    }

    public void setCount(int count) {
    
    
        this.count = count;
    }

    @Override
    public String toString() {
    
    
        return "Apple{" +
                "color='" + color + '\'' +
                ", count='" + count + '\'' +
                '}';
    }

    public Apple(String color, int count) {
    
    
        this.color = color;
        this.count = count;
    }
}
import java.util.Arrays;

public class Test04 {
    
    
    public static void main(String[] args) {
    
    
        test01();
    }

    public static Apple[] concat(Apple[] first, Apple[] second) {
    
    
        int firstLen = first.length;
        int secondLen = second.length;
        Apple[] c = new Apple[firstLen + secondLen];
        System.arraycopy(first, 0, c, 0, firstLen);
        System.arraycopy(second, 0, c, firstLen, secondLen);
        return c;
    }
    public static void test01(){
    
    
        Apple first1 = new Apple("red",1);
        Apple second1 = new Apple("yellow", 2);
        Apple[] first = new Apple[]{
    
    first1,second1};
        Apple first2 = new Apple("red",3);
        Apple second2 = new Apple("yellow", 4);
        Apple[] second = new Apple[]{
    
    first2,second2};
        Apple[] three = concat(first,second);
        System.out.println(Arrays.toString(three));
    }
}
Generics
    public static <T> T[] concatenate(T[] first, T[] second) {
    
    
        int firstLen = first.length;
        int secondLen = second.length;
        @SuppressWarnings("unchecked")
        T[] c = (T[]) Array.newInstance(first.getClass().getComponentType(), firstLen + secondLen);
        System.arraycopy(first, 0, c, 0, firstLen);
        System.arraycopy(second, 0, c, firstLen, secondLen);
        return c;
    }

    public static void test02() {
    
    
        //省略......跟test01()前面一样的内容
        Apple[] three = concatenate(first, second);
        System.out.println(Arrays.toString(three));
    }

Note that the generic solution does not apply to basic data types (int, boolean...)

15. Does Java support default parameter values?

Question:
In c++, it is common to see the following method definition (param3 defaults to false):

    void MyParameterizedFunction(String param1, int param2, bool param3=false);

Does java also support such a definition?
Answer:
The answer is no, but we can handle this situation of parameter default values ​​in many ways.

creator mode

To learn more about Creator Mode, click here for more details.
Using Creator Mode, you can set some parameters to have default values ​​and some parameters to be optional. For example:
import lombok dependency in pom.xml

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
@Getter@Setter
@AllArgsConstructor
@ToString
@Builder
public class Apple {
    
    
    private String color;
    private int count;
}

The Apple class can directly paste the lombok annotation @Builder to make it simple and trouble-free. Here is the detailed code.

public class Apple {
    
    
    private String color;
    private int count;

    Apple(String color, int count) {
    
    
        this.color = color;
        this.count = count;
    }

    public static AppleBuilder builder() {
    
    
        return new AppleBuilder();
    }

    public String getColor() {
    
    
        return this.color;
    }

    public int getCount() {
    
    
        return this.count;
    }

    public void setColor(String color) {
    
    
        this.color = color;
    }

    public void setCount(int count) {
    
    
        this.count = count;
    }

    public String toString() {
    
    
        return "Apple(color=" + this.getColor() + ", count=" + this.getCount() + ")";
    }

    public static class AppleBuilder {
    
    
        private String color;
        private int count;

        AppleBuilder() {
    
    
        }

        public AppleBuilder color(String color) {
    
    
            this.color = color;
            return this;
        }

        public AppleBuilder count(int count) {
    
    
            this.count = count;
            return this;
        }

        public Apple build() {
    
    
            return new Apple(this.color, this.count);
        }

        public String toString() {
    
    
            return "Apple.AppleBuilder(color=" + this.color + ", count=" + this.count + ")";
        }
    }
}
public class Test05 {
    
    
    public static void main(String[] args) {
    
    
        Apple a1 = new Apple.AppleBuilder().color("Eli").build();
        Apple a2 = new Apple.AppleBuilder().color("red").count(1).build();
        Apple a3 = new Apple.AppleBuilder().count(1).build();
        System.out.println(a1);
        System.out.println(a2);
        System.out.println(a3);
    }
}

output

Apple(color=Eli, count=0)
Apple(color=red, count=1)
Apple(color=null, count=1)

Method (constructor) overloading

Take constructor as an example:

    public Apple(String color, int count) {
    
    
        this.color = color;
        this.count = count;
    }
    public Apple(String color) {
    
    
        this.color = color;
    }

Apple apple1 = new Apple("a", 2);
Apple apple2 = new Apple("a");

Constructor overloading is more suitable when there are relatively few parameters; when there are relatively many parameters, you can consider using a static factory method or adding a parameter auxiliary object.

If it is a regular method overload, you can consider using parameter auxiliary objects, or renaming in various situations (for example, if there are multiple overload methods for opening bank cards, you can rename them as issuing bank cards, opening bank cards, etc. as needed) method).

Passing of null

When there are multiple default parameters, you can consider passing null. When the parameter is null, set the parameter to the default value. like:

public class Test06 {
    
    
    public static void apple(String a, Integer b, Integer c) {
    
    
        a = a == null ? "没有输入" : a;
        b = b == null ? 0 : b;
        c = c == null ? 0 : c;
        System.out.println(a + " " + b + " " + c + " ");
    }

    public static void main(String[] args) {
    
    
        apple("输入1", null, 3);
        apple(null,1,2);
    }
}

Output results

输入1 0 3 
没有输入 1 2 

multi-parameter mode

When there are multiple parameters and some parameters can be ignored and not set, you can consider using the multi-parameter method.
Friendly reminder: Try to write variable parameters at the end, otherwise overloading and writing an array of the same type will not work (although it is not impossible to change, it is best to write it down so as not to cause trouble in the future)

  • Optional parameter type conformance
public class Test07 {
    
    
    public static void apple(String color, Integer... numbers) {
    
    
        System.out.print(color);
        for (Integer number : numbers) {
    
    
            System.out.print(" " + number);
        }
    }

    public static void main(String[] args) {
    
    
        apple("red",1,2,3,4,5,6);
        // 输出:red 1 2 3 4 5 6
    }
}
  • Optional parameter types are inconsistent
    public static void main(String[] args) {
    
    
        apple("red", 1, 2, 3, 4, 5, 6);
        // 输出:red 1 2 3 4 5 6
        System.out.println(" ");
        apple("red", "1", 2, 3, "4", "5", null, 7);
    }

    public static void apple(String color, Object... numbers) {
    
    
        System.out.print(color);
        if (numbers != null) {
    
    
            for (Object number : numbers) {
    
    
                if (number instanceof Integer || number instanceof String) {
    
    
                    System.out.print(" " + number);
                }
            }
        }
    }

Use Map as parameter in method

When there are many parameters and most of them use default values, you can use Map as a parameter in the method.

import java.util.HashMap;
import java.util.Map;

public class Test08 {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("1", 1);
        map.put("2", 2);
        test01(map);
    }

    public static void test01(Map<String, Integer> map) {
        if (map != null && !map.isEmpty()) {
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
            }
        } else {
            System.out.println(map);
        }
    }
}

Top 100 Java Programming Questions—Basic Syntax Series Navigation

Top 100 Java Programming Questions—Basic Grammar Series (1)
Top 100 Java Programming Questions—Basic Grammar Series (2)
Top 100 Java Programming Questions—Basic Grammar Series (3)
I will write Series 4 when I have time.

If there are any mistakes, please let me know!
When reprinting or quoting the content of this article, please indicate the source and original author: Juzu Qingzhong;

Guess you like

Origin blog.csdn.net/weixin_44510587/article/details/129259254