String类中常用方法源码解析
2017-10-11 21:54
471 查看
初学String的时候完全不知道String里面有一大堆处理字符串的方法,硬是傻乎乎地自己去写,但是自从知道这些方法并且用了这么长时间一直咩有研究人家的具体实现,实在是丢人!学习人家的思路,帮助自己成长,本着这个目的开始了我的本篇博客
M1 length( )和 isEmpty( )
M2 equals( )
M3 startsWith()
po是子串的初始位置,to是原串的偏移位置,偏移量与子串长度之和不能大于原串长度
M4 endsWith()
M5 charAt(int index)
M6 hashCode()
哈希值用来唯一标识每个字符串,默认hash为0,如果字符串为空串,那么就返回0,如果不为空,就按照s[0]*31^(n-1) + s[1]*31^(n-2) + … + s[n-1]计算哈希值
M1 length( )和 isEmpty( )
public int length() { return count; } public boolean isEmpty() { return count == 0; }
M2 equals( )
public boolean equals(Object anObject) { if (this == anObject) {//同一个对象就直接返回true return true; } if (anObject instanceof String) {//"abc"和"ab"比较 String anotherString = (String) anObject; int n = count; if (n == anotherString.count) {//.count是系统方法,编译器可以通过 int i = 0; while (n-- != 0) { if (charAt(i) != anotherString.charAt(i)) return false; i++; } return true; } } return false; }
M3 startsWith()
public boolean startsWith(String prefix, int toffset) { int to = toffset; int po = 0; int pc = prefix.count; // Note: toffset might be near -1>>>1. if ((toffset < 0) || (toffset > count - pc)) { return false; } while (--pc >= 0) { if (charAt(to++) != prefix.charAt(po++)) { return false; } } return true; } public boolean startsWith(String prefix) { return startsWith(prefix, 0);//如果没有写int默认是0 }
po是子串的初始位置,to是原串的偏移位置,偏移量与子串长度之和不能大于原串长度
M4 endsWith()
public boolean endsWith(String suffix) { return startsWith(suffix, count - suffix.count); }
M5 charAt(int index)
public native char charAt(int index);//这个方法需要底层编写 这个方法的特殊之处在于他的返回值,可以是char单字符,也可以是unicode码整数
M6 hashCode()
/** Cache the hash code for the string */ private int hash; // Default to 0 public int hashCode() { int h = hash; if (h == 0 && count > 0) { for (int i = 0; i < count; i++) { h = 31 * h + charAt(i); } hash = h; } return h; }
哈希值用来唯一标识每个字符串,默认hash为0,如果字符串为空串,那么就返回0,如果不为空,就按照s[0]*31^(n-1) + s[1]*31^(n-2) + … + s[n-1]计算哈希值
相关文章推荐
- RecyclerView 的常用方法;工作原理与ListView比较;源码解析
- 基于ArrayList常用方法的源码全面解析
- 有关ArrayList常用方法的源码解析
- 54-55_数组_String类的常用方法_JDK源码分析_内存分析
- String类常用方法源码分析
- Java基础-String类的常用方法与对应源码
- String类常用方法源码分析
- 有关ArrayList常用方法的源码解析
- 有关LinkedList常用方法的源码解析
- String类的compareTo方法的源码解析
- 常见对象-String类的compareTo()方法的源码解析
- String类的compareTo()方法的源码解析
- java源码解析之String类的compareTo(String otherString)方法
- 常见对象_String类的compareTo()方法的源码解析
- String类的源码--常用的成员方法(一)
- String类的常用方法总结
- 关于String类的split方法解析
- XML DOM解析常用方法
- jquery源码解析:jQuery工具方法Callbacks详解
- 字符串String类、字符串缓冲区StringBuffer和StringBuilder、及常用方法