浏览 1282 次
锁定老帖子 主题:JDK代码的一个小bug
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-10-10
最后修改:2009-10-27
/** * Returns the position in this <code>SerialBlob</code> object where * the given pattern of bytes begins, starting the search at the * specified position. * * @param pattern the pattern of bytes for which to search * @param start the position of the byte in this * <code>SerialBlob</code> object from which to begin * the search; the first position is <code>1</code>; * must not be less than <code>1</code> nor greater than * the length of this <code>SerialBlob</code> object * @return the position in this <code>SerialBlob</code> object * where the given pattern begins, starting at the specified * position; <code>-1</code> if the pattern is not found * or the given starting position is out of bounds; position * numbering for the return value starts at <code>1</code> * @throws SerialException if an error occurs when serializing the blob * @throws SQLException if there is an error accessing the <code>BLOB</code> * value from the database */ public long position(byte[] pattern, long start) throws SerialException, SQLException { if (start < 1 || start > len) { return -1; } int pos = (int)start-1; // internally Blobs are stored as arrays. int i = 0; long patlen = pattern.length; while (pos < len) { if (pattern[i] == buf[pos]) { if (i + 1 == patlen) { return (pos + 1) - (patlen - 1); } i++; pos++; // increment pos, and i } else if (pattern[i] != buf[pos]) { pos++; // increment pos only } } return -1; // not found } 这个方法用于查找 blob 中是否存在 pattern 的字符数组,细看之下发现一个小 bug, 且看这段代码 int pos = (int)start-1; // internally Blobs are stored as arrays. int i = 0; long patlen = pattern.length; while (pos < len) { if (pattern[i] == buf[pos]) { if (i + 1 == patlen) { return (pos + 1) - (patlen - 1); } i++; pos++; // increment pos, and i } else if (pattern[i] != buf[pos]) { pos++; // increment pos only } } 当发现字符不匹配的情况下,应该将 i 置零,否则匹配结果是不正确的。当改为 int pos = (int)start-1; // internally Blobs are stored as arrays. int i = 0; long patlen = pattern.length; while (pos < len) { if (pattern[i] == buf[pos]) { if (i + 1 == patlen) { return (pos + 1) - (patlen - 1); } i++; pos++; // increment pos, and i } else if (pattern[i] != buf[pos]) { // 其实这个判断也没有必要 pos++; i = 0; // 在此处将 i 置 0 } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |