字符串数组中的单词数

时间:2013-10-14 13:59:02

标签: java arrays max limit

我可以在java中的String数组中存储多少个单词?我正在研究机器学习算法,我的要求是大约3000字。建议我处理该数据的任何替代方法,因为我已尝试使用数组,但它无法正常工作。

2 个答案:

答案 0 :(得分:3)

您已声明接收过ArrayIndexOutOfBounds异常,这是因为您使用的数据超出了规定的数组大小

String[] strings=new String[3000];
strings[3000]="something";//causes exception because strings[2999] is the last entry.

如果您知道需要多少条目,则声明该大小的数组,或者如果您需要可扩展的数组样式容器,请使用arraylist。

ArrayList<String> strings=new ArrayList<String>();
strings.add("Something"); //can be added as many times as you want (or that available memory will allow)

ArrayLists会在您向其添加项目时自动调整大小,当您需要列表行为(即事情在一个订单中)但它们不知道您将拥有多少项目时,它们是理想的。

然后,您可以根据需要从列表中检索项目,最常见的方法是;

String string=strings.get(0); //returns the first entry
int size=strings.size(); //tells you how many items are currently in the array list

注释

您可以通过告诉它预期的大小来提高ArrayList的性能,所以ArrayList<String> strings=new ArrayList<String>(3000);但这完全是可选的

答案 1 :(得分:0)

您可以使用以下代码找到在JVM上处理的内存量:

long maxBytes = Runtime.getRuntime().maxMemory();
System.out.println("Max memory: " + maxBytes / 1024 / 1024 + "M");

请注意,如果您想知道数组中可以包含多少字符串,请将整数除以~64,即String的平均长度。 (计算所有参考文献等)。

System.out.println("Max words: " + maxBytes / 64 + " words");

如果你有普通的机器,你应该至少有2GB RAM用于分配变量,平均单词约为30亿。

相关问题