-2

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

4

2 回答 2

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);这完全是可选的

于 2013-10-14T14:11:37.023 回答
0

您可以使用以下代码在 JVM 上找到您有多少内存可供使用:

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

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

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

如果你有普通的机器,你应该有至少 2GB 的 RAM 来分配变量,这大约是 3000 万个平均单词。

于 2013-10-14T14:04:08.500 回答