java常用类重写

  1. Object 类的toString()方法

 class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
class Test{
    public static void main(String[] args) {
        Person per = new Person("鲍星博", 21);
        System.out.println(per);
    }

}

输出为

我们不希望得到这样的结果,所以重写tostring方法;

@Override
public String toString() {
    return "名字为:"+this.name+"年龄为:"+this.age;
}

更改后输出为

得到了我们想要的结果。

2.equals方法

String类对象比较 使用的是 equals()方法,实际上String类的equals()方法就是覆写 Object类中的equals()方法

  • 基本数据类型的比较用 == (如: a == 3,b == 4, a == b,比较的是值是否相等)
  • 引用类型数据比较:调用 equals()方法进行比较

class Test{
    public static void main(String[] args) {
        Person per = new Person("鲍星博", 21);
        Person per2 = new Person("鲍星博", 21);
        System.out.println(per.equals(per2));
        //System.out.println(per);

    }

}

Per 和per2的值相同,但是输出结果为,这是因为equals比较的是引用对象的地址

我们想要他们相同,所以需要重写equals()函数

我们重写equals()

@Override
public boolean equals(Object obj) {
    if(obj ==null){
        return false;
    }
    if(obj == this){
        return true;
    }
    if(!(obj instanceof Person)){
        return false;
    }
    Person person = (Person)obj;
    return person.name.equals(this.name) && person.age==this.age;
}

之后输出结果为:

达到了我们想要的结果。

3.hashcode()

我们可以看到Object的hashcode()方法的修饰符为native,表明该方法是否操作系统实现,java调用操作系统底层代码获取哈希值。

public native int hashCode();

/**
 * Indicates whether some other object is "equal to" this one.
 * <p>
 * The {@code equals} method implements an equivalence relation
 * on non-null object references:
 * <ul>
 * <li>It is <i>reflexive</i>: for any non-null reference value
 *     {@code x}, {@code x.equals(x)} should return
 *     {@code true}.
 * <li>It is <i>symmetric</i>: for any non-null reference values
 *     {@code x} and {@code y}, {@code x.equals(y)}
 *     should return {@code true} if and only if
 *     {@code y.equals(x)} returns {@code true}.
 * <li>It is <i>transitive</i>: for any non-null reference values
 *     {@code x}, {@code y}, and {@code z}, if
 *     {@code x.equals(y)} returns {@code true} and
 *     {@code y.equals(z)} returns {@code true}, then
 *     {@code x.equals(z)} should return {@code true}.
 * <li>It is <i>consistent</i>: for any non-null reference values
 *     {@code x} and {@code y}, multiple invocations of
 *     {@code x.equals(y)} consistently return {@code true}
 *     or consistently return {@code false}, provided no
 *     information used in {@code equals} comparisons on the
 *     objects is modified.
 * <li>For any non-null reference value {@code x},
 *     {@code x.equals(null)} should return {@code false}.
 * </ul>
 * <p>
 * The {@code equals} method for class {@code Object} implements
 * the most discriminating possible equivalence relation on objects;
 * that is, for any non-null reference values {@code x} and
 * {@code y}, this method returns {@code true} if and only
 * if {@code x} and {@code y} refer to the same object
 * ({@code x == y} has the value {@code true}).
 * <p>
 * Note that it is generally necessary to override the {@code hashCode}
 * method whenever this method is overridden, so as to maintain the
 * general contract for the {@code hashCode} method, which states
 * that equal objects must have equal hash codes.
 *
 * @param   obj   the reference object with which to compare.
 * @return  {@code true} if this object is the same as the obj
 *          argument; {@code false} otherwise.
 * @see     #hashCode()
 * @see     java.util.HashMap
 */

HashSet的底层是通过HashMap实现的,最终比较set容器内元素是否相等是通过比较对象的hashcode来判断的

重写hashcode

@Override
public int hashCode() {
    int result  = name.hashCode();
    result = 17*result ;
    return result;
}

执行如下代码:

Person per = new Person("鲍星博", 21);
Person per2 = new Person("鲍星博", 21);
System.out.println(per.hashCode());
System.out.println(per2.hashCode());
Set set = new HashSet();
set.add(per);
set.add(per2);
//输出了一个对象,说明他们的hashcode相同,如果不重写,说明他们的hashcode不相同
System.out.println(set);

输出为

  1. String

String的对象不可变

String 类是被 final 修饰的,即 String 类不能被继承。

通过源代码可以看到,substring,replace 最后都是通过 new String(xxx) 来产生了一个新的 String 对象,最原始的字符串并没有改变

public String substring(int beginIndex, int endIndex) {

    if (beginIndex < 0) {

        throw new StringIndexOutOfBoundsException(beginIndex);

    }

    if (endIndex > value.length) {

        throw new StringIndexOutOfBoundsException(endIndex);

    }

    int subLen = endIndex - beginIndex;

    if (subLen < 0) {

        throw new StringIndexOutOfBoundsException(subLen);

    }

    return ((beginIndex == 0) && (endIndex == value.length)) ? this

            : new String(value, beginIndex, subLen);

}

public String replace(char oldChar, char newChar) {

    if (oldChar != newChar) {

        int len = value.length;

        int i = -1;

        char[] val = value; /* avoid getfield opcode */

        while (++i < len) {

            if (val[i] == oldChar) {

                break;

            }

        }

        if (i < len) {

            char buf[] = new char[len];

            for (int j = 0; j < i; j++) {

                buf[j] = val[j];

            }

            while (i < len) {

                char c = val[i];

                buf[i] = (c == oldChar) ? newChar : c;

                i++;

            }

            return new String(buf, true);

        }

    }

    return this;

}

public static void main(String[] args) {
    String str1 = "abc123456";
    //前闭后开
    String str2 = str1.substring(0,3);
    System.out.println(str1);
    System.out.println(str2);
}

输出为

  1. StringBuilder

StringBuilder 中的字符可变

我们假设使用 append 方法,该方法返回的依然是 StringBuffer 对象本身,说明他确实是值改变了

StringBuilder str3 = new StringBuilder("adoke152");
str3.append("666");
System.out.println(str3);

输出为

说明Stringbuilder的值变了。

String 对象的操作符“+”其实被赋予了特殊的含义,该操作符是 Java 中仅有的两个重载过的操作符。而通过反编译可以看到,String 对象在进行“+”操作的时候,其实是调用了 StringBuilder 对象的 append() 方法来加以构造

  1. String、StringBuffer、StringBuilder 对比

StringBuilder > StringBuffer > String

当然这个是相对的,不一定在所有情况下都是这样。

比如String str = “hello” + "world"的效率就比 StringBuilder st = new StringBuilder().append(“hello”).append(“world”)要高。

因此,如果是字符串相加操作或者改动较少的情况下,使用 String str = "hello" + "world" + ... 这种形式;土改时字符串相加比较多的话,建议使用 StringBuilder

线程安全

StringBuffer 线程安全的,StringBuilder 不是线程安全的

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值