0

I know php a little. and java much little.

I am creating 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

1

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

8 Comments

You should add the outer array would then be similar to MyData[] myData.
Which package is set in? It is giving cannot find symbol error
@mrN, java.util.Set My IDE just finds it for me and adds the import automagically. ;)
@Peter, Can you tell me the way to store the values in the two ways to have suggested. I am going nuts, trying to figure that out.
Which IDE are you using? I am using netbeans
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.