MAYA MAYA - 1 year ago 79
Java Question

Java create object of two parameters

I would like to know if is it possible to create an object of class with two parameters. Indeed, I want two store two values (double, int) with the same key in my hashmap as this:

{1 = (4.0, 5),.... }


So, I did something like that but I do not how to get the resultat above:

public class Dijkstra{
private final List<Integer> L;
private final int V;
private final int P;
private final double C;

public Dijkstra(){
L = new ArrayList<>();
}

//Create my object to put after in my hashmap
public Dijkstra(int P, double C){
this.P = P;
this.C = C;
}
.....
public Map mymethod() {
Map<Integer, Object> m = new HashMap<Integer, Object>();
}
}


So, I want to create an object of my class with my two parameters to put it in my hashmap.
How can I do this in java?

Thank you.

Answer Source

You need to create a class for that that will hold exactly these two values:

import java.util.*;

class MyValuePair {
    private int intValue;
    private double doubleValue;

    MyValuePair(double doubleValue, int intValue) {
        this.intValue = intValue;
        this.doubleValue = doubleValue;
    }

    //Getter and Setter as well as constructor(s) as needed
    public String toString() {
        return "(" + doubleValue + ", " + intValue + ")";
    }

}

public class Dijkstra {

    static Map<Integer, MyValuePair> map = new HashMap<>();

    public static void main(String[] args) {
        MyValuePair pair = new MyValuePair(4.0, 5);
        map.put(1, pair);
        System.out.println(map);
    }

}

So your value pairs go in MyValuePair and the objects of that class will go in the Map. You can create a new public class for it if you need (= in a new file with public keyword) or leave it in there as internal class.

Anything else with Lists and whatever you need will go in the Dijkstra class.

After the comment:

As said it is possible! But you do not want to do that. However this would be a code that would do the same where the Dijkstra class holds the values as well:

public class Dijkstra {

    static Map<Integer, Dijkstra> map = new HashMap<>();

    private double doubleValue;
    private int intValue;

    public Dijkstra(int intValue, double doubleValue) {
        this.intValue = intValue;
        this.doubleValue = doubleValue;
    }

    public String toString() {
        return "(" + doubleValue + ", " + intValue + ")";
    }

    public static void main(String[] args) {
        Dijkstra pair = new Dijkstra(4.0, 5);
        map.put(1, pair);
        System.out.println(map);
    }

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download