2012-02-18 45 views
0

我想舉個例子。如果我不知道數組會有多少元素?

import java.util.Scanner; 
public class ana 
{ 
    public static void main(String[] args) { 
     int[] array = new int[9]; // create array that have "9" elements 
     } 

} 

上面的例子的數組有9個元素,但我想創建無限數組。 如果我想這個時候我寫PHP我寫這篇文章的代碼:

<?php 
$example = array(); 
$example[] = 15; // auto numbering. PHP don't want number of array's element. 
$example[] = 20; 
?> 

又是什麼意思呢?

Auto[] array = {new Auto()}; 

我希望我明確自己。

回答

4

使用List(如ArrayList)。 Java有許多集合(List,Set,Map,Queue等),並有各種實現。通過閱讀collections tutorial瞭解如何使用它們。

1

您需要使用不同的數據結構,如Vector

+0

來吧。自JDK 1.2以來,ArrayList應該優於Vector。我們在JDK 7. – 2012-02-18 13:08:39

+0

@JBNizet這就是爲什麼我upvoted你的答案。 – 2012-02-18 13:16:20

1

我想你需要一個ArrayList:

ArrayList<Integer> as = new ArrayList<Integer>(); 
as.add(15); 
as.add(20); 

Auto[] array = {new Auto()};是類型自動與一個元素的數組。

1

嘗試使用ArrayList,在Java中使用List接口的可調整大小的實現。

1

在java中使用ArrayList

ArrayList<Integer> array = new ArrayList<Integer>(); 
相關問題