2

I want to make simple parameter-value pairs of the form (SomeClass, SomeNumber) where the 1st thing is a parameter and second thing is its value. SomeNumber can be a whole number, fraction, negative number etc. SomeClass can be String, Color or anything that can be paired with "SomeNumber" .

ex of employee and salaries. (John, 19.75), (David, 25.50), (Cathy, 102.50) ex for color codes (Color.black, 0), (Color.blue, 2) etc.

Is it a good idea? If not why? If yes, then how do I do it in Java?

SuperStar
  • 495
  • 2
  • 9
  • 22

5 Answers5

4

What you are talking about is Map

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

Try HashMap

Map<String,Double> myMap = new HashMap<String,Double>();
      |       |     
      |       |
SomeClass  SomeNumber

myMap.put("John", 19.75); 

SomeNumber num =  myMap.get("John");
Karthik T
  • 31,456
  • 5
  • 68
  • 87
3

I would recommend using a Map to achieve this type of behavior. For example for the employees you list:

Map<String, Double> employees = new HashMap<String,Double>(); 
employees.put("John", 19.75); 
employees.put("David", 25.50); 
employees.put("Cathy", 102.50);

You can then access the elements using the key.

double salary = employees.get("John");
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
2

You can either use a Map<String, Double> or you can create a class to hold the data. It is up to you to decide which alternative to implement based on the extent of functionality that you're looking for. If you're only looking for a storage mechanism, I would go with the Map, but if you want anything more than that (other methods etc.) I would go with the class.

Now, you seem to be merging these distinct 'name' and 'color code' ideas into one single entity. I would refrain from doing that. If you go with the map approach, I would maintain two different maps, one for the (name, salary) pairs and another for the color code data. If you decide to work with classes, I would create two different classes (perhaps both inheriting from the same base-class) to hold each set of data. Don't combine unrelated things into one entity!


Relevant documentation:

arshajii
  • 127,459
  • 24
  • 238
  • 287
1

You can use a HashMap or HashTable. There is a difference, but you can create a dictionary-like data structure (key-value pairs) using both concepts and Java utilities.

Community
  • 1
  • 1
Mr_Spock
  • 3,815
  • 6
  • 25
  • 33
0

Whether or not this is a good idea depends on what you are going to do with it. One of the easiest ways to do this in Java would be to create a simple object with two fields (and possibly getter and setter methods if you make the variables private), one for the string and one for the decimal value.

public class MyClass {
    public String value1;
    public double value2;

    public MyClass(String v1, double v2) {
        value1 = v1;
        value2 = v2;
    }
}
scaevity
  • 3,991
  • 13
  • 39
  • 54