gpt4 book ai didi

java - 循环内字符串串联并引发不允许的异常 : java. lang.Exception

转载 作者:行者123 更新时间:2023-12-02 06:23:50 25 4
gpt4 key购买 nike

在下面的代码中

for (UserSelection userSelection : filterList) {
String filterName = checkForDataHolder(userSelection
.getCriteriaName());
csvRow.append(filterName + ":");
List<String> list = userSelection.getCriteriaValues();
String filterval = "";
csvRow.append(DATA_DELIMITER);
for (String value : list) {

filterval += checkForDataHolder(value) + ", ";
}
if (filterval.indexOf(",") != -1) {
filterval = filterval.substring(0, filterval
.lastIndexOf(","));
}
csvRow.append(DATA_HOLDER + filterval + DATA_HOLDER);
csvRow.append(NEW_LINE);

}

这一行filterval += checkForDataHolder(value) + ", ";

导致循环内的字符串串联,为每个串联创建一个 StringBuffer。当放置在循环中时,这可能会导致创建和收集大量临时对象。如何在进入循环之前创建 StringBuffer 并在循环内附加到它?

也在下面的代码中

final StringBuffer csvRow = new StringBuffer();
csvRow.append(NEW_LINE);
csvRow.append(" ");

我想将字符串文字替换为字 rune 字以提高性能

考虑以下代码

public void writeHeader(List<String> headerColList) throws IOException {
this.header = headerColList;
String val;
try {
final StringBuffer csvRow = new StringBuffer();
for (int i = 0; i < header.size(); i++) {
if (i > 0) {
csvRow.append(DATA_DELIMITER);
}
val = checkForDataHolder(headerColList.get((i)));
if (!StringUtil.isEmpty(val)) {
csvRow.append(DATA_HOLDER + val + DATA_HOLDER);
}
}
if(!isHeaderProcessed) {
if(this.header != null) {
writer.write(csvRow.toString());
writer.write(NEW_LINE);
}
isHeaderProcessed = true;
}
} catch (Exception e) {
log.error(e);
}
}

我想考虑捕获更具体的异常类(异常的一个或多个子类)。这是最佳选择吗?

最佳答案

for (String value : list) {

filterval += checkForDataHolder(value) + ", ";
}

if (filterval.indexOf(",") != -1) {
filterval = filterval.substring(0, filterval
.lastIndexOf(","));
}

这是怎么回事?去掉尾随空格似乎效率很低。也许这更快:

bool Appended = false;
for (String value : list) {
if(Appended) { filterval += " ";}
filterval += checkForDataHolder(value) + ",";
Appended = true;
}

像沿着字符串扫描这样的事情比使用“”而不是“”更耗时。

异常(exception)确实是你的选择。您期待的不仅仅是内存分配错误吗?

关于java - 循环内字符串串联并引发不允许的异常 : java. lang.Exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20772432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com