常用类总结

2019-02-26  本文已影响0人  咖A喱

[TOC]

Object类

深浅拷贝

应用场景

解决措施

浅拷贝

例子
package model.two_week;

public class ObjectCloneDemo2 {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.setName("s1");
        s1.setAge(20);
        Teacher t1 = new Teacher();
        t1.setName("张三");
        t1.setAge(30);
        t1.setSubject("语文");
        s1.setTeacher(t1);
        System.out.println(s1);
        try {
            Student s2 = (Student) s1.clone();
            s2.setName("s2");
            s2.setAge(22);
            Teacher t2 = s2.getTeacher();
            t2.setAge(45);
            t2.setName("李四");
            t2.setSubject("数学");
            System.out.println(s2);
            System.out.println(s1);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }

}

class Person {
    protected String name;
    protected int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }


}

class Student extends Person implements Cloneable{
    protected Teacher teacher;

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", teacher" + teacher +
                '}';
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

class Teacher extends Person {
    protected String subject;

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    @Override
    public String toString() {
        return "{" +
                "name='" + name + '\'' +
                ", age=" + age+
                ", subject=" + subject +
                '}';
    }
}

输出结果

Student{name='s1', age=20, teacher{name='张三', age=30, subject=语文}}
Student{name='s2', age=22, teacher{name='李四', age=45, subject=数学}}
Student{name='s1', age=20, teacher{name='李四', age=45, subject=数学}}

可以看出,指向统一引用类型的s1和s2,当s2修改Teacher属性后,改变了s1

深拷贝

例子
package model.two_week;
public class ObjectCloneDemo {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.setName("s1");
        s1.setAge(20);
        Teacher t1 = new Teacher();
        t1.setName("张三");
        t1.setAge(30);
        t1.setSubject("语文");
        s1.setTeacher(t1);
        System.out.println(s1);
        try {
            Student s2 = (Student) s1.clone();
            s2.setName("s2");
            s2.setAge(22);
            Teacher t2 = (Teacher) t1.clone();//拷贝Teacher属性的第一种方式,后需要给s2设置Teacher
//            Teacher t2 = s2.getTeacher();//拷贝Teacher属性的第二种方式,直接从s2学生的Teacher属性获取
            t2.setAge(45);
            t2.setName("李四");
            t2.setSubject("数学");
            s2.setTeacher(t2);
            System.out.println(s2);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }

}
class Person implements Cloneable {

    protected String name;
    protected int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "{name:" + this.name + " age:" + this.age + "}";
    }

    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

class Student extends Person {
    protected Teacher teacher;

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", Teacher" + teacher +
                '}';
    }

}

class Teacher extends Person {
    protected String subject;

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }
}

输出结果

Student{name='s1', age=20, Teacher{name=张三', age=30, subject=语文}}
Student{name='s2', age=22, Teacher{name=李四', age=45, subject=数学}}
Student{name='s1', age=20, Teacher{name=张三', age=30, subject=语文}}

可见,实现了Cloneable接口的Teacher属性不会因为s2的改动而改动s1

equals()和hashcode()

public class equals_hashcode {
    public static void main(String[] args) {
        String s1 = "abcd";
        String s2 = "abcd";
        String s3 = new String("abcd");
        String s4 = new String("abcd");
        System.out.println("s1==s2 "+(s1==s2));//true,比较的是基本数据类型的内容
        System.out.println("s3==s4 "+(s3==s4));//false,比较的是两个引用类型的地址值
        System.out.println("s1==s3 "+(s1==s3));//false,比较的是两个不同数据类型
        System.out.println("s1.equals(s2) "+s1.equals(s2));//true,比较得是字符串的值
        System.out.println("s3.equals(s4) " + s3.equals(s4));//true,比较的是字符串的值
        System.out.println("abcd==abcd "+("abcd"=="abcd"));//true,比较的是两个基本数据类型的字符串的值
    }
}

其原因在于,继承Object的子类String复写了equals()方法

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;
}

上述equals()的实现方式在于hashCode()

public native int hashCode();

其native为本地方法,其默认返回对象的内存地址

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}
hash算法(哈希算法)
结论
  1. 调用equals()返回true的两个对象必须具有相同的哈希码
    1. 如果结果为false,证明其相同值的hash运算结果不一致,违背hash算法
  2. 如果两个对象的hashCode值相同,调用equals()不一定返回true
    1. 因为存在哈希碰撞现象

getClass和Class

toString

String类

compareTo与compare

compareTo

compare

异同

concat

说明文档

* Concatenates the specified string to the end of this string.
* <p>
* If the length of the argument string is {@code 0}, then this
* {@code String} object is returned. Otherwise, a
* {@code String} object is returned that represents a character
* sequence that is the concatenation of the character sequence
* represented by this {@code String} object and the character
* sequence represented by the argument string.<p>
* Examples:
* <blockquote><pre>
* "cares".concat("s") returns "caress"
* "to".concat("get").concat("her") returns "together"
* </pre></blockquote>
*
* @param   str   the {@code String} that is concatenated to the end
*                of this {@code String}.
* @return  a string that represents the concatenation of this object's
*          characters followed by the string argument's characters.
*/

源码

public String concat(String str) {
    int otherLen = str.length();
    if (otherLen == 0) {
        return this;
    }
    int len = value.length;
    char buf[] = Arrays.copyOf(value, len + otherLen);
    str.getChars(buf, len);
    return new String(buf, true);
}

例子​



public class Concat {
    public static void main(String[] args) {
        String i = "我";
        String is = "是";
        String a = "一位";
        String beauty = "美女";
        System.out.println(i.concat(is).concat(a).concat(beauty));//我是一位美女
        System.out.println(i);//我
        System.out.println(a.concat(beauty));//同样可以利用concat将字符串放置在此字符串之前//一位美女
    }
}

equals和equalslgnoreCase、contentEquals

源码比较

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;
}
public boolean contentEquals(CharSequence cs) {
        // Argument is a StringBuffer, StringBuilder
        if (cs instanceof AbstractStringBuilder) {
            if (cs instanceof StringBuffer) {
                synchronized(cs) {
                   return nonSyncContentEquals((AbstractStringBuilder)cs);
                }
            } else {
                return nonSyncContentEquals((AbstractStringBuilder)cs);
            }
        }
        // Argument is a String
        if (cs instanceof String) {
            return equals(cs);
        }
        // Argument is a generic CharSequence
        char v1[] = value;
        int n = v1.length;
        if (n != cs.length()) {
            return false;
        }
        for (int i = 0; i < n; i++) {
            if (v1[i] != cs.charAt(i)) {
                return false;
            }
        }
        return true;
    }

public boolean equalsIgnoreCase(String anotherString) {
    return (this == anotherString) ? true
            : (anotherString != null)
            && (anotherString.value.length == value.length)
            && regionMatches(true, 0, anotherString, 0, value.length);
}

其中equalsIgnoreCase调用的regionMatches方法如下:

public boolean regionMatches(int toffset, String other, int ooffset,
        int len) {
    char ta[] = value;
    int to = toffset;
    char pa[] = other.value;
    int po = ooffset;
    // Note: toffset, ooffset, or len might be near -1>>>1.
    if ((ooffset < 0) || (toffset < 0)
            || (toffset > (long)value.length - len)
            || (ooffset > (long)other.value.length - len)) {
        return false;
    }
    while (len-- > 0) {
        if (ta[to++] != pa[po++]) {
            return false;
        }
    }
    return true;
}

异同

例子

public class Equals {
    public static void main(String[] args) {
        System.out.println("Abc".equals("abc"));//false
        System.out.println("Abc".equalsIgnoreCase("abc"));//true
        System.out.println("Abc".contentEquals("abc"));//false
        System.out.println("Abc".contentEquals(new StringBuffer("Abc")));//true
    }
}

join

源码

  1. public static String join(CharSequence delimiter, CharSequence... elements) {
        Objects.requireNonNull(delimiter);
        Objects.requireNonNull(elements);
        // Number of elements not likely worth Arrays.stream overhead.
        StringJoiner joiner = new StringJoiner(delimiter);
        for (CharSequence cs: elements) {
            joiner.add(cs);
        }
        return joiner.toString();
    }
    
  2. public static String join(CharSequence delimiter,
            Iterable<? extends CharSequence> elements) {
        Objects.requireNonNull(delimiter);
        Objects.requireNonNull(elements);
        StringJoiner joiner = new StringJoiner(delimiter);
        for (CharSequence cs: elements) {
            joiner.add(cs);
        }
        return joiner.toString();
    }
    

说明文档

  1. 源码1 用于将指定的各个字符串连起来,如

    String.join("-", "Java", "is", "cool");
    *     // message returned is: "Java-is-cool"
    
  2. 源码2用于将字符串用特定字符分隔,同时删去最后的分隔符,如

    *     List<String> strings = new LinkedList<>();
    *     strings.add("Java");strings.add("is");
    *     strings.add("cool");
    *     String message = String.join(" ", strings);
    *     //message returned is: "Java is cool"
    *
    *     Set<String> strings = new LinkedHashSet<>();
    *     strings.add("Java"); strings.add("is");
    *     strings.add("very"); strings.add("cool");
    *     String message = String.join("-", strings);
    *     //message returned is: "Java-is-very-cool"
    

例子

public class Join {
    public static void main(String[] args) {
        String[] s1 = {"I","am","a","beauty"};
        System.out.println(String.join("-","I","am","a","beauty"));//I-am-a-beauty
        System.out.println(String.join("-",s1));
    }//I-am-a-beauty
}

trim

源码
public String trim() {
    int len = value.length;
    int st = 0;
    char[] val = value;    /* avoid getfield opcode */

    while ((st < len) && (val[st] <= ' ')) {
        st++;
    }
    while ((st < len) && (val[len - 1] <= ' ')) {
        len--;
    }
    return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
例子
public class Trim {
    public static void main(String[] args) {
        System.out.println("   abc    ".trim());
    }
}

输出结果为

abc

isEmpty

源码

public boolean isEmpty() {
    return value.length == 0;
}

例子

public class IsEmpty {
    public static void main(String[] args) {
        System.out.println("".isEmpty());//true
        System.out.println(" ".isEmpty());//false
    }
}

split

源码

  1. 对子字符串有限制,正整数表明最大返回数,负整数表明返回尽可能多,0可以排除尾随空字符串的所有子字符串
public String[] split(String regex, int limit) {
    /* fastpath if the regex is a
     (1)one-char String and this character is not one of the
        RegEx's meta characters ".$|()[{^?*+\\", or
     (2)two-char String and the first char is the backslash and
        the second is not the ascii digit or ascii letter.
     */
    char ch = 0;
    if (((regex.value.length == 1 &&
         ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
         (regex.length() == 2 &&
          regex.charAt(0) == '\\' &&
          (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
          ((ch-'a')|('z'-ch)) < 0 &&
          ((ch-'A')|('Z'-ch)) < 0)) &&
        (ch < Character.MIN_HIGH_SURROGATE ||
         ch > Character.MAX_LOW_SURROGATE))
    {
        int off = 0;
        int next = 0;
        boolean limited = limit > 0;
        ArrayList<String> list = new ArrayList<>();
        while ((next = indexOf(ch, off)) != -1) {
            if (!limited || list.size() < limit - 1) {
                list.add(substring(off, next));
                off = next + 1;
            } else {    // last one
                //assert (list.size() == limit - 1);
                list.add(substring(off, value.length));
                off = value.length;
                break;
            }
        }
        // If no match was found, return this
        if (off == 0)
            return new String[]{this};

        // Add remaining segment
        if (!limited || list.size() < limit)
            list.add(substring(off, value.length));

        // Construct result
        int resultSize = list.size();
        if (limit == 0) {
            while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
                resultSize--;
            }
        }
        String[] result = new String[resultSize];
        return list.subList(0, resultSize).toArray(result);
    }
    return Pattern.compile(regex).split(this, limit);
}
  1. 对子字符串无限制
public String[] split(String regex) {
    return split(regex, 0);
}

Array类

前提:

例子

public static class ArrayDemo {
   public static void main(String[] args){
      int[] arr ={2,6,8,4,7,1};
      System.out.println(arr[1]);
      getArr(arr);//打印数组
      print(getMax(arr));//获取数组最大值
      selectArr(arr);//排序数组
      getArr(arr);//打印数组
   }
   public static void getArr(int[] arr){
      System.out.print("[");
      for(int x =0 ;x<arr.length;x++){
        if(x!=arr.length-1) {
           System.out.print(arr[x]+",");
        }else
           System.out.print(arr[x]+"]");
      }
   }
   public static int getMax(int[] arr){
      int max=arr[0];
      for(int x=0;x<arr.length;x++){
         if(arr[x]>max){
            max=arr[x];
         }
      }return max;
   }
   public static void print(int num){
      System.out.println(num);
   }
   public static int getMin(int[] arr){
     int min=0;
      for(int x = 0;x<arr.length;x++){
        if(arr[x]<arr)
    }
   }
   public static void selectArr(int[] arr){
      for(int x=0;x<arr.length-1;x++){
         for(int y=x+1;y<arr.length;y++){
            if(arr[x]>arr[y]){
               int temp=arr[x];
               arr[x]=arr[y];
               arr[y]=temp;
            }
         }
      }
   }
}

常用静态方法

例子

public class ArrayTool2 {
    public static void main(String[] args) {
        int[] arr = {1,9,5,4,3};
        printArr(arr);
        Arrays.sort(arr);
        printArr(arr);
        System.out.println(Arrays.binarySearch(arr, 8));
        System.out.println(Arrays.binarySearch(arr, 4));
        Arrays.fill(arr, 1, 2, 5);
        printArr(arr);

    }
    public static void printArr(int[] var0) {
        System.out.print("[");

        for(int var1 = 0; var1 < var0.length; ++var1) {
            if (var1 != var0.length - 1) {
                System.out.print(var0[var1] + ",");
            } else {
                System.out.print(var0[var1] + "]\n");
            }
        }

    }
}

输出结果

[1,9,5,4,3]
[1,3,4,5,9]
-5
2
[1,5,4,5,9]
上一篇 下一篇

猜你喜欢

热点阅读