2011-05-11 94 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