解决java.lang.StringIndexOutOfBoundsException: String index out of range: -1错误问题
更新时间:2025年03月22日 11:29:49 作者:Archie_java
这篇文章主要介绍了解决java.lang.StringIndexOutOfBoundsException: String index out of range: -1错误问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
字符串截取下标越界
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1967)
出错代码
result.put("value", valueBuilder.toString().substring(0,valueBuilder.toString().length()-1));修改后代码
if (StringUtils.isNotBlank(valueBuilder.toString()) && valueBuilder.toString().length() >0){
result.put("value", valueBuilder.toString().substring(0,valueBuilder.toString().length()-1));
}心得:
- StringIndexOutOfBoundsException 异常源码如下:
/**
* Thrown by {@code String} methods to indicate that an index
* is either negative or greater than the size of the string. For
* some methods such as the charAt method, this exception also is
* thrown when the index is equal to the size of the string.
*/
public
class StringIndexOutOfBoundsException extends IndexOutOfBoundsException {
private static final long serialVersionUID = -6762910422159637258L;
/**
* Constructs a {@code StringIndexOutOfBoundsException} with no
* detail message.
*
* @since JDK1.0.
*/
public StringIndexOutOfBoundsException() {
super();
}
/**
* Constructs a {@code StringIndexOutOfBoundsException} with
* the specified detail message.
*
* @param s the detail message.
*/
public StringIndexOutOfBoundsException(String s) {
super(s);
}
/**
* Constructs a new {@code StringIndexOutOfBoundsException}
* class with an argument indicating the illegal index.
*
* @param index the illegal index.
*/
public StringIndexOutOfBoundsException(int index) {
super("String index out of range: " + index);
}
}总共有以下几个方法会抛出该异常:
String.substring() String.charAt() String.codePointAt() String.codePointBefore() String.subSequence() String.getChars() String.getBytes()
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Java TreeMap升序|降序排列和按照value进行排序的案例
这篇文章主要介绍了Java TreeMap升序|降序排列和按照value进行排序的案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-10-10
Spring Security OAuth2 token权限隔离实例解析
这篇文章主要介绍了Spring Security OAuth2 token权限隔离实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2019-11-11
如何解决SpringBoot2.6及之后版本取消了循环依赖的支持问题
循环依赖指的是两个或者多个bean之间相互依赖,形成一个闭环,SpringBoot从2.6.0开始默认不允许出现Bean循环引用,解决方案包括在全局配置文件设置允许循环引用存在、在SpringApplicationBuilder添加设置允许循环引用、构造器注入2024-10-10
SpringBoot配置Access-Control-Allow-Origin教程
文章介绍了三种配置Spring Boot跨域访问的方法:1. 使用过滤器;2. 在WebConfig配置文件中设置;3. 通过注解配置,作者分享了个人经验,并鼓励读者支持脚本之家2025-03-03
Spring Boot中使用RabbitMQ 生产消息和消费消息的实例代码
本文介绍了在SpringBoot中如何使用RabbitMQ进行消息的生产和消费,详细阐述了RabbitMQ中交换机的作用和类型,包括直连交换机、主题交换机、扇出交换机和头交换机,并解释了各自的消息路由机制,感兴趣的朋友一起看看吧2024-10-10


最新评论