java.lang.StackOverflowError
stack size 8M
堆栈溢出,查看是否是方法递归造成。
@JvmStatic
fun main(arg: Array<String>) {
val olderContent = "一二三四五六七八九十";
println("olderContent\t$olderContent\nreplaceAfterContent\t${testLength(olderContent, 5)}")
}
/***
* 测试二分法计算可容纳的个数
* @param name 原内容
* @param confirmLength 允许显示的个数
*/
fun testLength(name: String, confirmLength: Int): String {
if (originalName.equals("")) originalName = name
calculations++
println("第 ${calculations} 次计算")
var nameLength = name.length
var isExceeding = if (nameLength > confirmLength) {
1
} else if (nameLength < confirmLength) {
2
} else {
0
};
var typeName = when (isExceeding) {
1 -> {
"$nameLength 大于 $confirmLength"
}
2 -> {
"$nameLength 小于 $confirmLength"
}
else -> {
"$nameLength 等于 $confirmLength"
}
}
var nameHalf = 0;
var newName = name;
when (isExceeding) {
1 -> { // 大于
nameHalf = nameLength / 2 + 1
newName = if (nameHalf > 0) name.substring(0, nameHalf) else name
}
2 -> { // 小于
nameHalf = Math.abs(lastName.length - nameLength) / 2 + 1
// var subString = if (lastName.length > nameLength) lastName else originalName
newName = if (nameHalf > 0) originalName.substring(0, nameLength + nameHalf) else name
}
else -> { // 等于
println("完美 perfect name $name newName $newName")
}
}
println("name = $name nameLength $nameLength nameHalf $nameHalf confirmLength = $confirmLength typeName $typeName")
lastName = name
if (newName != name) {
return testLength(newName, confirmLength)
} else {
println("$calculations 次计算就压缩到范围内")
return name
}
}
打印结果:
name = 一二三四 nameLength 4 nameHalf 2 confirmLength = 5 typeName 4 小于 5
第 2658 次计算
name = 一二三四五六 nameLength 6 nameHalf 4 confirmLength = 5 typeName 6 大于 5
第 2659 次计算
name = 一二三四 nameLength 4 nameHalf 2 confirmLength = 5 typeName 4 小于 5
第 2660 次计算
name = 一二三四五六 nameLength 6 nameHalf 4 confirmLength = 5 typeName 6 大于 5
第 2661 次计算
name = 一二三四 nameLength 4 nameHalf 2 confirmLength = 5 typeName 4 小于 5
Exception in thread "main" java.lang.StackOverflowError
at java.io.Writer.write(Writer.java:157)
at java.io.PrintStream.write(PrintStream.java:525)
at java.io.PrintStream.print(PrintStream.java:669)
at java.io.PrintStream.println(PrintStream.java:823)
at MyTest.testLength(MyTest.kt:33)
at MyTest.testLength(MyTest.kt:72)
at MyTest.testLength(MyTest.kt:72)
如上所述典型的递归调用引起无线循环从而引起堆栈溢出,所以使用递归时需注意规避死循环的可能以免造成堆栈溢出。