我用JAVA写的字符统计小程序,请问为什么运行时出现OutOfMemoryError???

来源:百度知道 编辑:UC知道 时间:2024/07/02 19:57:57
源码如下:

import java.util.*;

public class StringTest {
public static void main(String[] args) {
String testString = "I am a good student.I come from China.Mr James Scott has a garage in Silbury and now he has just bought another garage in Pinhurst.Pinhurst is only five miles from SilBury, but Mr Scott cannot get a telephone for his new garage, so he has just bought twelve pigeons.Yesterday, a pigeon carried the first message from Pinhurst to Silbury.The bird covered the distance in three minutes. Up to now,MR Scott has sent a great many requests for spare parts and other urgent messages from ont garage to the other.In this way, he has began his own telephone service";
testString = testString.replace('.', ' ');
testString = testString.replace(',',' ');
String[] s = testString.split(" ");
System.out.println("共有单词数为: "+s.length+"个");
List<String>

你以下这段代码写的不好:

List<String> stringList = new ArrayList<String>();
for(int i=0;i<s.length;i++) {
String ss = s[i];
if(stringList.size()!=0) {
for(int j=0;j<stringList.size();j++) {
if(ss!=stringList.get(j)) {
stringList.add(ss);
}
}
} else {
stringList.add(ss);
}
}
System.out.println("不同的单词共有: "+stringList.size()+"个");

这个算法是有问题的,别的不说,单就
ss!=stringList.get(j) 这种写法就不好,对象间比较应该用equals方法,除非你想比较对象本身是否是一个对象,而不是对象的内容。

用下面的简单方法:

List<String> stringList = new ArrayList<String>();
for(int i=0;i<s.length;i++) {
if(!stringList.contains(s[i])) { //用List的contains方法来判断是否重复
stringList.add(s[i]); //只添加没有的
}
}
System.out.println("不同的单词共有: "+stringList.size()+"个");

超出范围了,你看看你 Sring里写了多少东西

你的程序有些错误。
我给你分析了分析,你的错误。
(题外话:Java中String判断要用equals方法)
(但