2011-05-11 55 views
0

我知道php有點。和Java很少。多維數組存儲多種數據類型

我正在創建一個小型應用程序來搜索文本區域中的文本並將結果存儲在數組中。

PHP中的數組看起來像這樣。

array(
    "searchedText" => "The text that is searched", 
    "positionsFound" => array(12,25,26,......), 
    "frequencies" => 23 //This is total words found divided by total words 
); 

但是,java不支持具有多種數據類型的數組。在上面的數組中,只有第二個元素「positionFound」具有可變長度。

後來我需要遍歷這個數組並創建一個包含上述所有元素的文件。

請指導我

+0

我可以建議你花時間閱讀了Sun的Java教程的時間開始與 「新到Java」 頁面 - HTTP ://www.oracle.com/technetwork/topics/newtojava/new2java-141543.html。從長遠來看,這將爲您節省很多痛苦... – 2011-05-11 10:54:48

回答

3

Java確實支持對象。你必須定義一個類如

class MyData { 
    String searchedText; 
    Set<Integer> positionsFound; 
    int frequencies; 
} 

List<MyData> myDataList = new ArrayList<MyData>(); 
// OR 
MyData[] myDataArray = new MyData[number]; 

而且你可以使用這個結構來保存你的數據。還有其他一些有用的方法,如構造函數和toString(),我建議你使用IDE來生成這些方法。

將此數據寫入文件時,您可能會發現JSon是一種自然格式可供使用。


我建議你看看GSon這是一個不錯的JSon庫。

GSon文檔,這裏是一個例子

class BagOfPrimitives { 
    private int value1 = 1; 
    private String value2 = "abc"; 
    private transient int value3 = 3; 
    BagOfPrimitives() { 
    // no-args constructor 
    } 
} 

(串行化)

BagOfPrimitives obj = new BagOfPrimitives(); 
Gson gson = new Gson(); 
String json = gson.toJson(obj); 

==> JSON爲{ 「值1」:1, 「VALUE2」: 「ABC」}

請注意,您不能使用循環引用序列化對象,因爲這會導致無限遞歸。

(反序列化)

BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class); 

==> OBJ2,就像OBJ

+0

+1爲更快 – Thomas 2011-05-11 10:25:01

+2

您應該添加外部數組然後將類似於'MyData [] myData'。 – Thomas 2011-05-11 10:25:46

+0

哪個包被設置?它給無法找到符號錯誤 – mrN 2011-05-11 10:36:10