有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java字符串数组中的字数

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


共 (2) 个答案

  1. # 1 楼答案

    您已声明收到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)
    

    ArrayList会在您向其添加项目时自动调整大小,当您需要列表行为(即,事情是按顺序排列的)但事先不知道将有多少项目时,ArrayList非常理想

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

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

  2. # 2 楼答案

    通过使用以下代码,您可以找到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万个平均字