Reputation: 3102
I am hesitating what is the suitable data structure to save the following data form:
So that if I have a result_number I can -
So what is the appropriate data structure?
Upvotes: 1
Views: 2461
Reputation: 726639
If the number of intervals is small, use a class
with three members (min
, max
, and message
), store them in a list, and run a linear search.
If the number of intervals is overwhelming, and the timing requirements make linear search prohibitive, create an interval tree, ans associate the messages with its leaf nodes.
If the intervals are not overlapping, you can create an interval class with two ends, and store interval objects in a TreeMap
using their left boundary to compare intervals. With this TreeMap
in hand, you can find an interval quickly by calling floorEntry
on the number that you are trying to locate and checking if the returned interval key overlaps the value that you are looking for.
Upvotes: 2
Reputation: 1500875
It sounds like you want...
(Wait for it...)
... a class with two integers and a string.
public final class RangeValidation {
private final int minimum;
private final int maximum;
private final String message;
public RangeValidation(int minimum, int maximum, String message) {
if (minimum > maximum) {
throw new IllegalArgumentException("Invalid min/max combination");
}
if (message == null) {
throw new NullPointerException();
}
this.minimum = minimum;
this.maximum = maximum;
this.message = message;
}
// You can tweak this API, of course...
// it could throw an exception instead, or return an empty string for
// success, etc.
public String validate(int value) {
return value < minimum || value > maximum ? mesasge : null;
}
}
Of course you may want to make this implement an interface to fit in with a more general validation framework etc... but the important point is that you've already neatly describe what you want your type to contain - so you just need to write it.
Also note that this counts the maximum
value as inclusive - you may wish to make it exclusive, in order to be able to represent empty ranges. (That does make it harder to represent a range for which Integer.MAX_VALUE
is valid though...)
Upvotes: 7
Reputation: 425073
In java a "data structure" is represented by a class with fields. The class may have methods that use these fields.
Try this:
public class MyClass {
private int min;
private int max;
private String message;
public void testNumber(int number) {
if (number >= min && number <= max) {
System.out.println(message);
}
}
}
You should probably have a constructor to set the values of the fields and I would recommend making the fields final
.
Upvotes: 3