Multidimensional Arrays to store multiple data types
I know php a little. and java much little.
I am creating 开发者_JAVA百科a small application to search a text in a text area and store the result in a array.
The array in PHP will look like this.
array(
"searchedText" => "The text that is searched",
"positionsFound" => array(12,25,26,......),
"frequencies" => 23 //This is total words found divided by total words
);
But, java does not support array with multiple data types. In the above array, only the second element "positionFound" is of variable length.
Later on I need to iterate through this array and create a file including all above mentioned elements.
Please guide me
Java does support Objects. You have to define a Class like
class MyData {
String searchedText;
Set<Integer> positionsFound;
int frequencies;
}
List<MyData> myDataList = new ArrayList<MyData>();
// OR
MyData[] myDataArray = new MyData[number];
And you can use this structure to hold your data. There are other methods which are helpful such as constructors and toString() and I suggest you use your IDE to generate those.
When writing this data to a file, you might find JSon a natural format to use.
I suggest you look at GSon which is a nice JSon library.
From the GSon documentation, here is an example
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj
精彩评论