2

What is the best way in Java to store a value and one piece of corresponding information about that value? As great as it might be to use, I have a feeling that a simple POJO is a bit of overkill here.

Problem is as follows: I have a form object which contains different types of "weight" values. Some of these weights may need to show up in bold on my JSP page, and at other times they do not.

One way to represent this information could be to use an array of size 2, where the first value is the weight and the second value is "Y" or "N" to represent its bold state.

Another option is to use a List which also contains two values. Or to use an enum, or a custom type of object etc. etc.

From a design point of view, what is the cleanest, most effective way to represent this basic form of data?

wild_nothing
  • 2,845
  • 1
  • 35
  • 47

4 Answers4

3

Why not use HashMap? Use the weight as your key and the value as either true or false.

Map<Double, Boolean> weight = new HashMap<Double, Boolean>();
john_science
  • 6,325
  • 6
  • 43
  • 60
Jj Tuibeo
  • 773
  • 4
  • 18
2

With weight it's easy: take a primitive double, if you want to mark it with NO make it negative.

boolean no = weight < 0;
boolean yes = weight > 0;
double realWeight = Math.abs(weight);
john_science
  • 6,325
  • 6
  • 43
  • 60
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

Have you considering using a HashMap? This allows you to associate two pieces of data in a key/pair set. For instance, for each weight (a Double value) you could associate a boolean that says whether it should be bold or not:

HashMap formData = new HashMap<Double, Boolean>();

formData.put(0.005, true);
formData.put(0.333, true);
formData.put(1.5, false);
formData.put(0.25, true);

You could grab any individual value like so:

formData.get(0.005);      // returns 'true'

Or you could iterate through all of the values like so:

Iterator it = formData.iterator();
while (it.hasNext()) {
    Double singleForm = (Double)it.next();
    System.out.println(singleForm.getKey() + " is " + singleForm.getValue());
}

A HashMap is an extremely fast, lightweight, and standard data structure.

Community
  • 1
  • 1
john_science
  • 6,325
  • 6
  • 43
  • 60
1

Use CollectionsMap, something like this.

Map<String, String> dataMap1 = new HashMap<>();

Map<pojo, boolean> dataMap2 = new HashMap<>();
dataMap2.put(pojo1, true);
...

Key and Value pair, store the key as Object and Value as properties about that object

Reference : Collections API, Map API

wchargin
  • 15,589
  • 12
  • 71
  • 110
Vinay Veluri
  • 6,671
  • 5
  • 32
  • 56