datatype converter on hashmap value doesn't work

edited March 2018 in Questions about Code

I'm trying to create a list of countries where each country is supposed to have multiple values and use those values. While trying to access the values I keep getting the wrong datatype. Trying to change the datatype to int doesn't work.

  HashMap<String, HashMap> countries = new HashMap<String, HashMap>();
  for (int i=0; i<destCountryArray.length; i++) {

    HashMap<String, Float> country = new HashMap<String, Float>();

    countries.put(destCountryArray[i], country);

    country.put("x", i*20.0);
    country.put("y", i*10.0);
  }


for (Map.Entry hm : countries.entrySet()) {
  print(hm.getKey() + " is ");
  println(hm.getValue());
}

  for (int i = 0; i< destCountryArray.length; i++) {

      println("get x = " + (countries.get(destCountryArray[i])).get("x"));          // this prints well
      //println(int((countries.get(destCountryArray[i])).get("x")));                    // this creates an error
      //int xSource = 1;
     int xSource = (countries.get(destCountryArray[i])).get("x");                      // also doesn't work
  }

Answers

  • Can you post a runable example?

  • // Based on Example Written by Casey Reas and Ben Fry
    // Edited by Tom Bar-Gal
    
    
    
    //particlesystem()
    //addparticle()
    //particle()
    
    
    import java.util.Map;  
    
    
    // ========== Table Data Stuff 
    
    Table table;
    int k = 0;
    String[] destCountryArray = new String[0];
    String[] sourceCountryArray = new String[0];
    
    String destCountry = "";
    String prevDestCountry = "";
    
    String sourceCountry;
    
    // ========
    
    
    int maxParticles = 12000;
    
    ParticleSystem ps;
    ParticleSystem ps2;
    
    int n = 0, n2=0;
    int emmitMultiplyer = 1;
    int emmitFreq = 1;
    float particleSpeed = 0.002;
    
    float locationX = 250;
    float locationY = 450;
    
    int[] sourceX = {10, 40, 200, 400, 700};
    int[] destX = {300, 600, 300, 600, 600};
    int[] amount = {10, 100, 500, 800, 1000};
    int highestAmount = max(amount);
    
    // a,b,c... max*a/{a+b+c...}
    
    ParticleSystem[] PSystems;
    
    
    void setup() {
      size(1200, 800);
    
      //=============== load table and create an array of countries
    
      table = loadTable("asylum_seekers.csv", "header");
    
      destCountryArray = (String[]) append(destCountryArray, "Israel");
    
      for (TableRow row : table.rows()) {
        //println("going over row" + row.getString("Country / territory of asylum/residence"));
        String tempCountryHolder = row.getString("Country / territory of asylum/residence");
        //println("Got a temp country holder" + tempCountryHolder);
        boolean exists = countryExists(tempCountryHolder);
        if (exists==true) {
          //println("exists, skipping");
          continue;
        }
        //println("Appending "+tempCountryHolder+" to list of length " +destCountryArray.length);
        destCountryArray = (String[]) append(destCountryArray, tempCountryHolder);
        //println("destCountryArray length = "+ destCountryArray.length);
      }
    
      //============================ country hashmaps =============
    
    
    
    
      HashMap<String, HashMap> countries = new HashMap<String, HashMap>();
      for (int i=0; i<destCountryArray.length; i++) {
    
        HashMap<String, Float> country = new HashMap<String, Float>();
    
        countries.put(destCountryArray[i], country);
    
        country.put("x", i*20.0);
        country.put("y", i*10.0);
      }
    
    
    for (Map.Entry hm : countries.entrySet()) {
      print(hm.getKey() + " is ");
      println(hm.getValue());
    }
    
      PSystems = new ParticleSystem[destCountryArray.length];
      //frameRate(30);
      //colorMode(RGB,255,255,255,255);
      for (int i = 0; i< destCountryArray.length; i++) {
    
          println("get x = " + (countries.get(destCountryArray[i])).get("x"));
          //println(int((countries.get(destCountryArray[i])).get("x")));
          //int xSource = 1;
         int xSource = (countries.get(destCountryArray[i])).get("x");
    
    
        // Particle Systems syntax = multiplyer, source, destination, amount);
        PSystems[i] = new ParticleSystem(1, new Vector3D(xSource, 100, 0), new Vector3D(i*40+40, 500, 0), 1/(i+1));
        //println("PSystems " + i + " is " +PSystems[i]);
      }
    
      //ps = new ParticleSystem(1, new Vector3D(width/2, height/2, 0));
      //ps2 = new ParticleSystem(1, new Vector3D(100, 200, 0));
    
      smooth();
    }
    
    void draw() {
    
      background(250);
      //ellipse(locationX, locationY, 5, 5);
      //ellipse(width/2, height/2, 5, 5);
      //ellipse(100, 200, 5, 5);
      //println(PSystems.length);
    
      for (int i = 0; i<destCountryArray.length; i++) {
        //println(PSystems[i]);
        PSystems[i].run();
      }
    
    
      for (int i = 0; i<emmitMultiplyer; i++) {
        for (int k = 0; k<destCountryArray.length; k++) {
          if (frameCount % (k+1) == 0) {
            PSystems[k].addParticle();
            n++;
          }
        }
      }
    
      n2+=emmitMultiplyer;
    
      fill(0);
      text("Frame rate: "
        + int(frameRate), 10, 20);
      //println(n);      
    }
    
    
    
    
    // ==============================//  A simple Particle class  // ===============================================//
    
    
    
    
    class Particle {
    
      Vector3D loc;
      Vector3D des;
      Vector3D vel;
      Vector3D acc;
      Vector3D locHome, b, c;
      float relativeSpeed;
    
      float r;
      float timer;
    
      float t=0.0; 
    
      // Another constructor (the one we are using here)
      Particle(Vector3D l, Vector3D m) {
    
        //acc = new Vector3D(0,0.0005,0);  // particle acceleration
    
        acc = new Vector3D(0, 0, 0); //  new Vector3D(random(-0.1, 0.1), random(-0.02, 0), 0);
        loc = l.copy();
        des = m.copy();
        locHome = l.copy();
        locHome.x = locHome.x+random(-2, 2);
        locHome.y = locHome.y+random(-2, 2);
        des.x = des.x+random(-2, 2);
        des.y=des.y+random(-2, 2);
        relativeSpeed = random(0.5, 1.2);
    
        r = random(0.9, 2.3);  // particle radius
        timer = 10000.0;   // particles lifespan
        // * emmitMultiplyer = number of living
    
        b=new Vector3D(locHome.x+random(-20, 20), locHome.y+random(120, 180), 0);
        c=new Vector3D(des.x+random(-20, 30), des.y-random(120, 180), 0);
      }
    
      void run() {
        update();
        render();
      }
    
      // Method to update location
      void update() {
    
        if (t>=1)
          return;
    
        // https : // www.processing.org/reference/bezierPoint_.html
    
        loc.x = bezierPoint(locHome.x, b.x, c.x, des.x, t);
        loc.y = bezierPoint(locHome.y, b.y, c.y, des.y, t);
    
        t = lerp(t, 1, particleSpeed*relativeSpeed);
        //t+=particleSpeed*relativeSpeed; 
    
        // curvePoint(a, b, c, d, t)
        // vel.add(acc);
        // loc.add(vel);
        //timer -= 1.0;
      }
    
      // Method to display
      void render() {
        ellipseMode(CENTER);
        noStroke();
        fill(70, 255);
    
        ellipse(loc.x, loc.y, r, r);
      }
    
      // Is the particle still useful?
      boolean dead() {
        //    if (timer <= 0.0||t>=1.0) {
        if (t>=0.95) {
          return true;
        } else {
          return false;
        }
      }
    }
    
    
    // ==============================//  A ParticleSystem  // ===============================================// 
    
    
    
    // A class to describe a group of Particles
    // An ArrayList is used to manage the list of Particles
    class ParticleSystem {
    
      ArrayList particles;    // An arraylist for all the particles
      Vector3D origin;        // An origin point for where particles are birthed
      Vector3D dest;
      int freq;
    
      //ParticleSystem( number of particles / frame, source, destination, frequency);
      ParticleSystem(int num, Vector3D v, Vector3D d, float f) {
        particles = new ArrayList();              // Initialize the arraylist
        origin = v.copy();     // Store the origin point
        dest = d.copy();
    
        //if (frameCount % (1/f) == 0){
        for (int i = 0; i < num; i++) {
          particles.add(new Particle(origin, dest));    // Add "num" amount of particles to the arraylist
        }
        //}
      }
      void run() {
        // Cycle through the ArrayList backwards b/c we are deleting
        for (int i = particles.size()-1; i >= 0; i--) {
          Particle p = (Particle) particles.get(i);
          p.run();
          if (p.dead()) {
            particles.remove(i);
            n--;
          }
        }
      }
    
      void addParticle() {
        particles.add(new Particle(origin, dest));
      }
    
      //void addParticle(Particle p) {
      //  particles.add(p);
      //}
    
      // A method to test if the particle system still has particles
      boolean dead() {
        if (particles.isEmpty()) {
          return true;
        } else {
          return false;
        }
      }
    }
    
    
    //=================================================== Class Country
    
    
    // ================================================ Simple Vector3D Class
    public class Vector3D {
    
      public float x;
      public float y;
      public float z;
    
      Vector3D(float x_, float y_, float z_) {
        x = x_; 
        y = y_; 
        z = z_;
      }
    
      Vector3D(float x_, float y_) {
        x = x_; 
        y = y_; 
        z = 0f;
      }
    
      Vector3D() {
        x = 0f; 
        y = 0f; 
        z = 0f;
      }
    
      void setX(float x_) {
        x = x_;
      }
    
      void setY(float y_) {
        y = y_;
      }
    
      void setZ(float z_) {
        z = z_;
      }
    
      void setXY(float x_, float y_) {
        x = x_;
        y = y_;
      }
    
      void setXYZ(float x_, float y_, float z_) {
        x = x_;
        y = y_;
        z = z_;
      }
    
      void setXYZ(Vector3D v) {
        x = v.x;
        y = v.y;
        z = v.z;
      }
    
      public float magnitude() {
        return (float) Math.sqrt(x*x + y*y + z*z);
      }
    
      public Vector3D copy() {
        return new Vector3D(x, y, z);
      }
    
      public Vector3D copy(Vector3D v) {
        return new Vector3D(v.x, v.y, v.z);
      }
    
      public void add(Vector3D v) {
        x += v.x;
        y += v.y;
        z += v.z;
      }
    
      public void sub(Vector3D v) {
        x -= v.x;
        y -= v.y;
        z -= v.z;
      }
    
      public void mult(float n) {
        x *= n;
        y *= n;
        z *= n;
      }
    
      public void div(float n) {
        x /= n;
        y /= n;
        z /= n;
      }
    
      public void normalize() {
        float m = magnitude();
        if (m > 0) {
          div(m);
        }
      }
    
      public void limit(float max) {
        if (magnitude() > max) {
          normalize();
          mult(max);
        }
      }
    
      public float heading2D() {
        float angle = (float) Math.atan2(-y, x);
        return -1*angle;
      }
    
      public Vector3D add(Vector3D v1, Vector3D v2) {
        Vector3D v = new Vector3D(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z);
        return v;
      }
    
      public Vector3D sub(Vector3D v1, Vector3D v2) {
        Vector3D v = new Vector3D(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z);
        return v;
      }
    
      public Vector3D div(Vector3D v1, float n) {
        Vector3D v = new Vector3D(v1.x/n, v1.y/n, v1.z/n);
        return v;
      }
    
      public Vector3D mult(Vector3D v1, float n) {
        Vector3D v = new Vector3D(v1.x*n, v1.y*n, v1.z*n);
        return v;
      }
    
      public float distance (Vector3D v1, Vector3D v2) {
        float dx = v1.x - v2.x;
        float dy = v1.y - v2.y;
        float dz = v1.z - v2.z;
        return (float) Math.sqrt(dx*dx + dy*dy + dz*dz);
      }
    }
    
    boolean countryExists(String tempCountryHolder) {
    
      for (int i = 0; i < destCountryArray.length; i++) {
        //println("comparing '" +tempCountryHolder +"' with '"+destCountryArray[i] + "'");
        if (tempCountryHolder.equals(destCountryArray[i]) == true) {
          //println("found : "+ tempCountryHolder);
          return true; // it exists
        } //if
      } //for
      return false ; // not found
    }//func
    
  • And the data?

  • Do they not teach unit testing any more?

  • @koogs sorry I'm a designer not a programmer they don't teach us code everything I know is through tutorials and forums like this one :)

    Link to the data :) https://www.dropbox.com/s/ubu4ny5aygsjnsr/asylum_seekers.csv?dl=0

  • I suspect that the problem is that Java is not inferring the datatypes for Map.Entry. If you are going to use generics then I suggest you use them throughout like this.

    import java.util.*;
    
    HashMap<String, HashMap<String, Float>> countries = 
      new HashMap<String, HashMap<String, Float>>();
    
    HashMap<String, Float> c0 = new HashMap<String, Float>();
    c0.put("Berlin", 3.426354);
    c0.put("Hamburg", 1.739117);
    c0.put("Munich", 1.260391);
    c0.put("Cologne", 0.963395);
    countries.put("Germany", c0);
    
    HashMap<String, Float> c1 = new HashMap<String, Float>();
    c1.put("Paris", 2.138551);
    c1.put("Marseille", 0.794811);
    countries.put("France", c1);
    
    HashMap<String, Float> c2 = new HashMap<String, Float>();
    c2.put("London", 9.75);
    c2.put("Birmingham", 2.453);
    c2.put("Manchester", 1.903);
    countries.put("Great Brittain", c2);
    
    // Display all
    for(Map.Entry<String, HashMap<String, Float>> country : countries.entrySet()){
      println(country.getKey());
      HashMap<String, Float> cityMap = country.getValue();
      for(Map.Entry<String, Float> cityEntry : cityMap.entrySet()){
        println("\t" + cityEntry.getKey() + "\t   Pop: " + cityEntry.getValue());
      }
    }
    

    Which gives the output

    Great Brittain
        London     Pop: 9.75
        Manchester     Pop: 1.903
        Birmingham     Pop: 2.453
    France
        Marseille      Pop: 0.794811
        Paris      Pop: 2.138551
    Germany
        Munich     Pop: 1.260391
        Berlin     Pop: 3.426354
        Hamburg    Pop: 1.739117
        Cologne    Pop: 0.963395
    
  • edited March 2018

    what does Vector3D give you that PVector doesn't?

    another personal bugbear

      println("get x = " + (countries.get(destCountryArray[i])).get("x"));          // this prints well
      //println(int((countries.get(destCountryArray[i])).get("x")));                    // this creates an error
      //int xSource = 1;
     int xSource = (countries.get(destCountryArray[i])).get("x");                      // also doesn't work
    

    those comments would be a lot more useful if you knew they were there but they are far too far to the right and you don't know you need to scroll

    one T in Britain.

    this HashMap<String, HashMap<String, Float>>() is kind of terrible. you know what 'shape' the data is, write a class to hold it rather than using that inner hashmap dogpile.

    Year,Country / territory of asylum/residence,Origin,RSD procedure type / level,Tota pending start-year,of which UNHCR-assisted(start-year),Applied during year,decisions_recognized,decisions_other,Rejected,Otherwise closed,Total decisions,Total pending end-year,of which UNHCR-assisted(end-year)
    2000,Zimbabwe,Afghanistan,G / FI,0,0,5,5,0,0,0,5,0,0
    2000,South Africa,Afghanistan,G / FI,8,1,0,0,0,0,0,,8,0
    2000,Uzbekistan,Afghanistan,U / FI,265,265,2156,747,0,112,327,1186,1235,1235
    2000,United States of America,Afghanistan,G / EO,196,0,225,151,0,31,68,250,171,0
    2000,United States of America,Afghanistan,G / IN,193,0,218,182,0,51,40,273,150,0
    2000,Ukraine,Afghanistan,G / FI,40,0,662,275,0,412,0,687,23,0
    2000,Turkey,Afghanistan,U / FI,67,67,81,29,0,24,49,102,46,46
    2000,Turkmenistan,Afghanistan,U / FI,416,416,169,126,0,121,210,457,128,128
    2000,Tajikistan,Afghanistan,G / FI,2172,30,165,112,0,0,1992,2104,233,40
    2000,Thailand,Afghanistan,U / AR,0,0,2,1,0,1,0,2,0,0
    2000,Thailand,Afghanistan,U / FI,5,0,25,14,1,2,4,21,9,5
    2000,Syrian Arab Rep.,Afghanistan,U / FI,311,0,94,62,0,138,180,380,25,0
    

    ^ some example data (dropbox killed my browser trying to display 129,000 lines of csv in an html table)

  • edited March 2018

    for example. this does what your original code does, adds countries with an x and y for each, puts them in a hash, gets them out again. you can add any other data to the class as members, rather than as entries into a hash.

    // example data
    String[] destCountryArray = {
      "Afghanistan",
      "United States of America",
      "Turkey",
      "Thailand",
      "Sweden"
    };
    
    HashMap<String, Country> countries = new HashMap<String, Country>();
    
    void setup() {
    
      // initialise the countries hash
      for (int i = 0 ; i < destCountryArray.length; i++) {
        String name = destCountryArray[i];
        // use name as key
        countries.put(name, new Country(name, i * 20.0, i * 10.0));
      }
    
      // print the countries hash
      for (String key : countries.keySet()) {
        Country c = countries.get(key);
        println(key + " is at " + c.x + ", " + c.y);
      }
    }
    
    // the class
    class Country {
      String name;
      float x, y;
      // more things here?
    
      Country(String name, float x, float y) {
        this.name = name;
        this.x = x;
        this.y = y;
      }
    }
    
  • oh ok that makes much more sense, I'm going to try this and report back asap

    I'm still confused though as to why the hashmap of hashmaps doesn't return the correct data type

  • because you don't tell it what type the inner hashmap entries are

    HashMap<String, HashMap> countries =
        new HashMap<String, HashMap>();
    

    vs quark's

    HashMap<String, HashMap<String, Float>> countries = 
        new HashMap<String, HashMap<String, Float>>();
    

    when you extract the entries from the outer map it only knows it's a hashmap, not what that hashmap contains.

    but you don't really want a hashmap here.

Sign In or Register to comment.