2013-05-26 24 views
1

我正在嘗試搜索數組中的第一個空插槽。你能否用parseInt()引號做到這一點,還是我會用「stobar[b] == null」?在數組中搜索空插槽

int[] stobar = new int[100]; 
for(int b = 0; b < stobar.length; b++) 
{ 
    if(stobar[b] == Integer.parseInt("")) 
    { 
     stobar[b] = row; 
     stobar[b+1] = col; 
     break; 
    } 
} 
+1

注意這個例子不可能自足:如果初始化在同一行和迭代器上方對整個陣列在下一個單元格中,您將始終在每個單元格中具有默認值。 Integer的默認值爲'null',而int的默認值爲'0'。 – rethab

回答

8

兩個時間都不去上班,你想要的方式,因爲你有一顆靈長類動物的陣列,它只能容納整數。如果你想要一個不同的空值,你需要改爲Integer[]

1

您可以使用

Integer[] stobar = new Integer[100]; 
... 

for(int b=0; b<stobar.length; b++) 
{ 
    if(stobar[b]==null) 
    { 
     stobar[b] = row; 
     stobar[b+1] = col; 
     break; 
    } 
} 

你確定要使用靜態數組?也許一個ArrayList更適合你。

我不知道你有什麼,但看看下面的實現

public class Point 
{ 
    private int row; 
    private int col; 

    public Point(int row, int col) 
    { 
    this.row = row; 
    this.col = col; 
    } 

    public static void main(String[] args) 
    { 
    List<Point> points = new ArrayList<Point>(); 

    ... 
    Point p = new Point(5,8); 
    points.add(p); 
    ... 
    } 

}