Common methods of java object class & String class and common methods

Java Object class

The Java Object class is the parent class of all classes, that is to say, all Java classes inherit Object, and subclasses can use all methods of Object.
The Object class is located in the java.lang package and will be automatically imported when compiling. When we create a class, if it does not explicitly inherit a parent class, it will automatically inherit Object and become a subclass of Object.

Commonly used important methods of the class

  • public String toString()
    returns the string representation of the object
    Example:
public class Test {
    
    
    public static void main(String[] args) {
    
    
        Person person = new Person();
        //调用person对象的方法toString()
        String s = person.toString();
        //com.yls.demo1.Person@1b6d3586  这是对象在内存中的“地址”
        System.out.println(s);
        //com.yls.demo1.Person@1b6d3586
        System.out.println(person);  
        //得出结论 输出语句中必须(默认)调用toString()方法 
        //无权更改,sun公司规定死的
        //输出语句System.out.println(对象)调用对象的toString()
        //System.out.println(对象)==System.out.println(对象.toString())
    }
}

In actual development, the toString() method of the parent class is generally rewritten, and instead of the default object address representation, we create our own string representation

  • Override the parent class toString() method
public class Person {
    
    
    /**
     * 重写父类的方法toString
     * 返回字符串
     * @return
     * 重写方法的目标:方法中,返回类中成员变量的值
     */
    private  String name;
    private  int age;
    public Person(){
    
    }
    public Person(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString(){
    
    
        return name +":" + age;
    }
}


public class Test {
    
    
    public static void main(String[] args) {
    
    
        Person person = new Person("李四",25);
        //调用person对象的方法toString()
        String s = person.toString();
        //李四:25
        System.out.println(s);
        //李四:25
        System.out.println(person);  
    }
}
  • boolean equals(Object obj)
    compares whether two objects are equal, java believes that any object is comparable
    object class method equals source code:
public boolean equals(Object obj) {
    
    
        return (this == obj);
    }
    //this指调用者,obj指传入的Object对象参数

By default, the memory address of the object is compared
, but the address of the general object is not comparable, so we need to rewrite our equals method to establish our own comparison form of the object. The
example is as follows:


    @Override
    public boolean equals(Object obj){
    
    
        //健壮性判断1,如果obj的值为null,比较的另一个对象不存在
        if (obj == null) {
    
    
            return false;
        }
        //健壮性判断2,判断this和obj是不是一个对象,如果是就直接返回true
        if(this == obj){
    
    
            return true;
        }
        //这里涉及一个多态的问题,
        //obj应该向下转型为Person才可以调用age
        //同时需注意安全性判断
        if (obj instanceof Person) {
    
    
            Person p = (Person) obj;
            return this.age == p.age;
        }
        //不是Person 没有可比性
        return false;
    }


 Person person = new Person("李四",25);
 Person person1 = new Person("王二", 25);
 boolean b = person.equals(person1);
 System.out.println(b);   //true

String string class

java.lang.Object
java.lang.String
All Implemented Interfaces:
Serializable , CharSequence , Comparable < String >
Inherit the Object class and implement three interfaces. The string object is a constant. Once created, it cannot be modified.
Just write " " in the program. Objects of the String class

Implementation principle of
string The string data type does not exist in Java, and its implementation principle is that the
"abc" represented by the char[] array is actually char[] ch = {'a', 'b', 'c' } to indicate that
after the JDK9 version, in order to save memory, the char array becomes a byte array.
JDK8 and before are all char arrays

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    
    
    /** The value is used for character storage. */
    private final char value[];   //成员变量char数组
	......

The modifier final before the array indicates the final array. Once its address is established, it will be locked (constant) for thread safety.

Properties of String Constants

   public static void main(String[] args) {
    
    
        String a = "abc";
        String s = new String("abc");  //new对象新开一片堆,与a String对象中的数组地址不一样
        System.out.println(a == s);   //false
        System.out.println("---------------");

        /**
         * s1保存的是String对象
         * s2 = "hello" 和s1中的字符串在内存中的数组表现是一样的 ,JVM为了节约内存两者共用
         * s1的地址赋值给s2
         */
        String s1 = "hello";
        String s2 = "hello";
        System.out.println(s1==s2); //true
        System.out.println("---------------");

        /**
         * s3 和 s4都是变量,变量在编译的时候,javac不确定变量的计算结果是什么
         * 运行的时候jvm会为s3+s4的结果新开内存空间
         */
        String s3 = "hhh";
        String s4 = "ooo";
        String s5 ="hhhooo";
        System.out.println(s5 ==(s3+s4)); //false
        System.out.println("---------------");
        /**
         * "hhh" "ooo" 是常量,值在编译期间就已经确定
         * 运行时期不会建立新的内存空间
         */
        System.out.println(s5==("hhh"+"ooo"));//true

    }

String constructor

  • String(byte[] bytes)
    Constructs a new String by decoding the specified byte array using the platform's default charset.

  • String (byte[] bytes, int offset, int length)
    byte array is converted to a string, using the platform's default character set, the parameter off represents the beginning of the array, and len represents the number of conversions

  • String(byte[] bytes, String charsetName)
    charsetName is a code table that you can specify yourself. For example, specify GBK
    GBK code on the idea. In order to distinguish it from English,
    2 bytes of negative value means that a Chinese character
    utf-8 is 3 bytes represent a Chinese character

    public static void Byte2string(){
    
    
        /**
         * String(byte[] bytes)
         * 通过使用平台的默认字符集解码指定的字节数组来构造新的 String
         * wiodows 中文版 默认字符集是GBK  ,idea启动时为jvm添加启动参数会把默认字符集改为UTF-8
         */
        byte[] b ={
    
    97,98,99};
        String s = new String(b);
        System.out.println(s); //abc

        //数组的一部分转换为字符串
        //从索引1开始,两个字符
        String s1 = new String(b,1,2);
        System.out.println(s1);//bc
    }
    public static void main(String[] args) {
    
    
        Byte2string();
    }

Only the byte array is related to the encoding table, and nothing else

  • String(char[] value)
    turns an array into a string

  • String (char[] value, int offset, int length)
    array is converted to a string, the parameter off represents the beginning of the array, and len represents the number of conversions

    public static void Char2string(){
    
    
        //构造方法,数组转为字符串
        char ch [] ={
    
    'a','b','c','q'};
        String s = new String(ch);
        System.out.println(s);//abcq
        //数组转为字符串转一部分
        String s1 = new String(ch, 1, 2);
        System.out.println(s1);//bc
    }

Common methods of the String class

Judgment method of String class

  • boolean equals(Object anObject)
    Compares this string with the specified object.
  • boolean equalsIgnoreCase(String anotherString)
    compares this String with other Strings, ignoring case
  • boolean startsWith(String str)
    determines whether the string starts with another string, and returns true if it is
  • boolean endsWith(String str)
    determines whether the string ends with another string, and returns true if it is
  • boolean contains(CharSequence s)
    Returns true if and only if this string contains the specified sequence of char values.
  • boolean isEmpty()
    determines whether the length of the string is 0, and returns true if and only if it is 0
 /**boolean equals(Object anObject)
         * 字符串直接的比较
         * String继承自Object,重写父类方法
         */
        boolean b  = "abcd".equalsIgnoreCase("ABCD");
        boolean c  = "abcd".equals("abcD");
        boolean d = "Hello,world".startsWith("Hello");
        boolean e = "world,Hello".endsWith("Hello");
        boolean f = "Hello fine".contains("fi");
        boolean ff = "Hello fine".contains("if");

        System.out.println(b);  //true
        System.out.println(c);  //false
        System.out.println(d);  //ture
        System.out.println(e);  //true
        System.out.println(f);  //true
        System.out.println(ff); //false

The equals method rewritten by sun is as follows

 public boolean equals(Object anObject) {
    
    
        if (this == anObject) {
    
    
            return true;
        }
        if (anObject instanceof String) {
    
    
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
    
    
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
    
    
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

The method to obtain the String class, the return value is not necessarily

  • int length() returns the length of the string, the number of characters in the string
  • char charAt(int index) returns a single character at the specified index
  • int indexOf(String str) returns the specified string, the index of the first occurrence in the current string
  • int lastindexOf(String str) returns the specified string, the index of the last occurrence in the current string
  • String substring(int start, int end) intercepts a string, and the parameters indicate the start and end indexes, where the interception includes the start index and does not include the end index
 		//int length()返回字符串长度,字符串中字符的个数
        int length = "abcde".length();
        System.out.println(length);// 5
        //char charAt(int index) 返回指定索引上的单个字符
        char chr = "hedfgg".charAt(3);
        System.out.println(chr); //f
        //int indexOf(String str)返回指定的字符串,在当前字符串中第一次出现的索引
        int index = "hello word so smart".indexOf("s");
        System.out.println(index);//11
        //以s第一次出现为准
        int index1 = "hello word so smart".indexOf("so");
        System.out.println(index1);//11
        //int lastindexOf(String str)返回指定的字符串,在当前字符串中最后一次出现的索引
        int index2 = "hello word so smart".lastIndexOf(" ");
        System.out.println(index2);//13
        //String substring(int start,int end)截取字符串,参数表示开始和结束索引,其中截取包含开始索引,不包含结束索引
        String str = "hello world";  //是锁死的字面量”hello world”
        String str1 = str.substring(2,5);  //如果不赋值的化仍然是原str ,需要赋值新的字符串
        System.out.println(str1);//llo
        System.out.println(str.substring(2,5));//llo

Comparison method of String class

  • public int compareTo(String anotherString)
    Compares two strings lexicographically (natural order). Comparisons are based on the Unicode value of each character in the string.
		/**
         * int compareTo(String anotherString) 按字典顺序(自然顺序)比较两个字符串
         */
        String str1 = "abcdef";
        String str2 = "abdefg";
        String str3 = "abcdef";
        String str4 = "abcdeg";
        /**
         * 返回值是int
         * 返回值为负,调用者小
         * 返回值为正,调用者大
         * 返回值为0,一样大
         */
        int i = str1.compareTo(str2);
        int j = str1.compareTo(str3);
        int k = str1.compareTo(str4);
        System.out.println(i);  //-1  底层是数组,数组中一个一个的比较 c<d为负,后边就不比了
        System.out.println(j);  //0   一个一个的比较,都相同 返回0
        System.out.println(k);  //-1  f<g为负 

Methods of the String class, remove spaces, replace, cut

  • String trim() removes the spaces on both sides of the string, but does not remove the spaces in the middle
  • String replace(String oldString, String newString) replaces the string
  • String []split("rule string") cuts the string
		// String trim() 去掉字符串两边的空格,中间的空格不去掉
        String str =" aa c bb d ";
        String s = str.trim();
        System.out.println(s); //aa c bb d

        //String []split("规则字符串") 对字符串进行切割
        String str1Split ="aa,bb,cc,dd";
        String[] strings = str1Split.split(",");
        for(int i =0; i< strings.length;i++){
    
    
            System.out.println(strings[i]);    // aa  bb cc dd
        }
        //String replace(String oldString,String newString)替换字符串
        String strReplace = "how are you ?";
        String replace = strReplace.replace("o", "ee");
        System.out.println(replace);  //heew are yeeu ?

String class regular expression related

  • character class:

    • [abc]This position of the string can only be abc
    • [^abc]This position of the string cannot be abc
    • [a-zA-Z]This position of the string must be a letter, 52 characters
    • [^a-zA-Z]This position of the string must not be a letter, 52 characters
  • Number class:

    • [0-9]This position of the string can only be a number
    • [^0-9]This position of the string cannot be a number
    • [\d]Equivalent to[0-9]
    • [\D]Equivalent to[^0-9]
  • Predefined characters:

    • . matches all characters
    • [\d]Equivalent to[0-9]
    • [\D]Equivalent to[^0-9]
    • [\w]Text characters, including numbers, letters, and underscores[a-zA-Z0-9_]
    • [\W]Text characters, cannot contain numbers, letters, underscores[^a-zA-Z0-9_]
  • Quantifiers :

    • X{m} The character X can only appear m times a{3}
    • X{m,} The character X appears at least m times
    • X{m,n} The character X appears at least m times and no more than n times
    • X? The character X appears once, or not at all
    • X* X This character appears zero or more times
    • X+ X This character appears at least once (appears one or more times)

String regular matching check

  • boolen matches(String regex)
    tells whether this string matches the given regular expression.
    If the match is successful, it returns true; if it fails, it returns false.
    Example:
/**
     *  检查邮箱
     *  规则需求 :
     * @ 前面 : 可以是字母,数字,_  
     * @ 后面 : 数字,字母  sina qq 126 1393 yahoo gmail 
     * . 固定 : com  cn org  edu gov 字母  
     */
public static void stringMethod2(){
    
    
    String email = "[email protected]";
    // "[a-zA-Z0-9] == [\\w] \\两个\其中一个代表转义"
    //"[\\w]+" 表示[\w] 匹配一次或多次
    //(\\.[a-z]+)+ 表示(\\.[a-z]+)这个匹配组匹配一次或多次  比如.com.cn
    String reg = "[\\w]+@[a-z0-9]+(\\.[a-z]+)+"; 
    boolean b = email.matches(reg);
    System.out.println(b);

}
/**
     *  正则表达式检查手机号是否合法
     * 规则需求
     *  开头必须是1,长度固定11
     *  第二位3 4 5 6 7 8 9
     *  第三位 必须是都是数字
     */
public static void stringMethod(){
    
    
    String tel = "13800138000";
    //定义正则的规则,也是字符串
    String regex = "1[3459678][0-9]{9}";
    //正则规则,和字符串校验
    //String类的方法 matches()
    boolean b = tel.matches(regex);
    System.out.println(b);
}
  • String[] split(String regex)
    Splits this string into matches of the given regular expression.
   public static void stringMethod3(){
    
    
        String str = "as123d387654w5465fasfr234567sa";
        String[] strings = str.split("\\d+");
        for (int i = 0; i < strings.length; i++) {
    
    
            System.out.println(strings[i]);
        }  //as d w fasfr sa
        System.out.println("================");
        String ip = "192.....168.....35.121";
        String[] ipArray = ip.split("\\.+");
        for (int i = 0; i < ipArray.length; i++) {
    
    
            System.out.println(ipArray[i]);  
        }// 192  168   35 121
    }
  • String replaceAll(String regex, String replacement)
    Replaces each substring of this string that matches the given regular expression with the given replacement.
  • String replaceFirst(String regex, String replacement)
    Replaces the first substring of this string that matches the given regular expression with the given replacement.
 public static void stringMethod4(){
    
    
        String str = "as123d387654w5465fasfr234567sa";
        //字符串中的所有数组,换成#
        String repString = str.replaceAll("\\d+","#");
        System.out.println(repString);//as#d#w#fasfr#sa

        String first =  str.replaceFirst("\\d+","#");
        System.out.println(first);//as#d387654w5465fasfr234567sa
    }

In the development of String Builder
programs, string concatenation is often encountered. The direct way is to use the "+" symbol to realize the direct splicing of Strings. However, this method will create a String object every time it is executed, which is inefficient and time-consuming. Waste of space. This problem can be avoided by using the StringBuilder class.
public final class StringBuilder
extends Object
implements Serializable, CharSequence
is a variable character sequence (character array). This class provides an API with StringBuffer, but synchronization is not guaranteed.
When creating an object, the initialization length of the array in StringBuilder is 16 characters

StringBuilder automatically expands the array, the new array is realized, and the elements in the original array are copied to the new array.

Conclusion: No matter how you do string operations, there will always be only one array inside StringBuilder

The StringBuilder class is a thread-unsafe class that runs fast

StringBuffer is a thread-safe class that runs slowly and is used by multi-threaded programs

The construction methods of the two classes are exactly the same as the other methods.

 	   StringBuilder builder = new StringBuilder(20);
        builder.append("helo");
        System.out.println(builder); //helo
        builder.insert(3,"world");
        System.out.println(builder);//helworldo

        StringBuilder builder1 = new StringBuilder(16);
        System.out.println(builder1.append("hello").append("world").append("  ").append("over"));// helloworld  over

Guess you like

Origin blog.csdn.net/A52091/article/details/124319950