提高制作简单阵列的效率



我是初学者,所以这绝对是常识,所以我来这里询问。

如果我想制作一个只包含不同单词的非常大的数组,比如这个

adjectives[0] = "one";
adjectives[1] = "two";
adjectives[2] = "three";
adjectives[3] = "four";
adjectives[4] = "five";

这只是一个小例子,我实际制作的数组非常大。当然,我不必硬编码,也不必一行一行地写。我怎样才能更有效地做到这一点?

编辑:

问题在继续讨论这个话题时发生了轻微的变化。

我想打开一个类似的txt文件

A
B
C
D
E

数组列表,该列表由程序吐出到控制台中,用于另一个程序。

基本上是textfile.txt->program->arraylist.txt

使用for()循环:

String[] adjectives = new String[6]; //first letter of a non-final variable should be lowercase in java
for(int i = 0; i < adjectives.length; i++) { //loop index from 0 to the arrays length
    adjectives[i] = Integer.toString(i) //you could also use an int[]
}

完成。

还可以看看这个:https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

如果您试图简单地分配升序,则使用for循环:

int[] adjectives = int[5];
//replace 5 with whatever you want
for(int x = 0; x < adjectives.length; x++){
    adjectives[x] = x
} 

如果你想把没有递增顺序的字符串/对象放在那里,那么你可以把赋值语句压缩成一行:

String[] adjectives = {"hey", "there", "world", "hello"}

如果单词是从一个文本变量中混合而来的,您可以将其拆分:

String text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit";
String[] words = text.split("[ n]");
System.out.println(Arrays.toString(words));

您可以使用for循环并将lop的索引解析为字符串:

    final String[] foo = new String[10];
    for (int i = 0; i < foo.length; i++) {
        foo[i] = Integer.toString(i);
    }
    System.out.println(Arrays.toString(foo));

逐行读取文本文件,并使用BufferedReader将读取的每一行存储到ArrayList中`

import java.io.*;
import java.util.ArrayList;

class TxtFileToArrayList 
{
 public static void main(String args[])
  {
    ArrayList lines = new ArrayList();
    try{
    // Open the file     
    FileInputStream fstream = new FileInputStream("text.txt"/*file path*/);
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String readLine;
    //Read File Line By Line
    while ((readLine = br.readLine()) != null)   {
          lines.add(readLine);// put the line in the arrayList
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
    }
  }
}

`或使用readAllLines()

您可以使用arraylist,然后如果您真的只想要数组,则将arraylist转换为数组数据类型——

List<String> ls=new ArrayList<String>();
        for(int i=0;i<=Integer.MAX_VALUE-1;i++)
            ls.add(Integer.toString(i));
String array[]=ls.toArray(new String[ls.size()]);

最新更新