一开始拿到这个题目是很懵的,重写一个String类的题目描述也太模糊了,重写是为了实现什么功能呢?再加上我大学期间用的最多最熟悉的是C++,Java学过用过但是很快就忘了,所以就去B站找了学习视频看,讲的很详细,我只看了String类相关的部分,学习完了就是参考网上的代码,完成输入到输出的过程。必须要知道的是,String类不可被继承,也就是说不能通过子类继承父类来重写String类的方法,自己写一个MyString类只是帮助自己学习和加深理解,如果非要替代原有的String类的话要从jre改,没有必要哈。
String类:final类,不可被继承,代表不可变的字符序列,支持序列化,可以比较大小
具体代码如下:
package test1;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Locale;
/*
* String类:final类,不可被继承,代表不可变的字符序列
* 支持序列化,可以比较大小
*/
public class MyString implements Serializable, Comparable<String>, CharSequence {
//serialVersionUID 用来表明类的不同版本间的兼容性,数字表明这个序列化的类的唯一标识
private static final long serialVersionUID = -204188373852348874L;
private final char[] value;
public MyString() {
value = new char[0];
}
public MyString(String str) {
this.value = str.toCharArray();
}
public MyString(char[] value) {
this.value = value;
}
public MyString(byte[] bytes) {
this.value = new char[bytes.length];
for(int i = 0; i < bytes.length; i++) {
this.value[i] = (char) bytes[i];
}
}
public MyString(char value[], int offset, int count) {
if(offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if(count <= 0) {
if(count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if(offset <= value.length) {
this.value = new char[0];
return;
}
}
if(offset > value.length-count) {
throw new StringIndexOutOfBoundsException(offset);
}
this.value = Arrays.copyOfRange(value, offset, count);
}
//求字符串长度
public int length() {
return value.length;
}
//返回某索引处的字符
public char charAt(int index) {
if(index > this.value.length || index < 0) {
throw new StringIndexOutOfBoundsException(index);
}
return this.value[index];
}
//从指定区间摘出子串
public CharSequence subSequence(int start, int end) {
if(start < 0) {
throw new StringIndexOutOfBoundsException(start);

最低0.47元/天 解锁文章
191





