2016-08-04 27 views
0

我是初學者,所以這絕對是常識,所以我來這裏問。提高製作簡單陣列的效率

如果我想打一個很大的數組,只是包含不同的話,像這樣的

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

這只是一個小例子,我實際上使陣列是非常大的。當然,我不必對此進行硬編碼,並逐一完成每一行。我怎樣才能更有效地做到這一點?

編輯:

問題已經稍微轉移,而仍然在這個話題上。

我想打開一個txt文件這樣



Ç
d
Ë

到一個數組列表,其吐出由程序到控制檯,用於另一個程序。

基本上TextFile.txt的 - >程序 - > arraylist.txt

+2

您使用循環。 – Eran

+0

只需使用'for'循環。 –

+0

對於動態大小,最好使用ArrayList。 – Blobonat

回答

0

您可以使用for循環並解析羅布泊的索引字符串:

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)); 
0

使用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[] 
} 

完成。

也看看這個:如果你想將字符串/對象

int[] adjectives = int[5]; 
//replace 5 with whatever you want 

for(int x = 0; x < adjectives.length; x++){ 
    adjectives[x] = x 
} 

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

0

如果你想簡單地分配上行號碼,然後使用for循環那裏沒有一些增量訂單,那麼你可以將賦值語句壓縮到一行:

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

個給的詞從文本正在添加的變量,你可以只把它分解:

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

您可以使用ArrayList,然後如果你真的想陣列才轉換到ArrayList的數組datatype--

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()]); 
+1

這是創建數組的不必要的低效方法。使用列表或使用數組;不要同時使用兩者。 –

0

逐行讀取文本文件線和各讀取線存儲到一個ArrayList與一個BufferedReader '

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()