1

I need to parse an xml file in java and store it in an array for sorting later. The xml file has this format

<Experiments>
    <Experiment ID="312" RIndex="3" DIndex="3">40231</Experiment>
    <Experiment ID="481" RIndex="2" DIndex="5">23801</Experiment>
    <Experiment ID="102" RIndex="1" DIndex="5">41231</Experiment>
</Experiments>

For each experiment, the RIndex, DIndex and experiment values has to be stored. The most straight forward way I thought was a 2D array, but there's a function where I need to sort by one of those attributes (RIndex, DIndex or Experiment value). I thought of using ArrayList of collections too. Is this the best way to do it?

Abubakkar
  • 15,488
  • 8
  • 55
  • 83
kidA
  • 23
  • 1
  • 5

4 Answers4

1

I'd definitely use an ArrayList at the top level, and provide a custom Comparator to sort the values according to whatever sorting criteria you have in mind. For usage of comparators see:

Choosing how to store the values is going to be your most important choice. The best options are likely to be:

  • Define a class Experiment which contains the fields you need. This will be most efficient.
  • Store each experiment result in a HashMap which maps fields to values. This will be less efficient but might be a useful approach if you have different types of experiment with different attributes etc.
Community
  • 1
  • 1
mikera
  • 105,238
  • 25
  • 256
  • 415
  • thanks. what I was iffy about was the comparator part but the link you gave clarified it – kidA Oct 14 '12 at 06:27
0

Create a simple class with the 3 values, then create appropriate Comparators for each of the sorting cases, then stuff them in to an ArrayList and use the proper Comparator.

Will Hartung
  • 115,893
  • 19
  • 128
  • 203
0

You can create a class Experiment with instance variables ID,RIndex,DIndex and Value and then implement the Comparator interface by which you can sort your objects of Experiment class.(Assuming you know how to use Comparator)

Abubakkar
  • 15,488
  • 8
  • 55
  • 83
0

Since performance seem to be critical I'm sure you will setup benchmarks. They will tell you what is the best way.

The obvious way to do this would be to put the data in a SortedSet, so you don't have a separate sorting step. Should be way faster then reading anything from a file so I guess you should be fine. with that.

You'd need to create a simple class containing all the relevant values and possibly some additional id, to make each value unique.

This class should implement the Comparable interface, or if you need sorting with different criteria you can provide separate Comparators.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348