简体   繁体   中英

Is there a way to perform addition/subtraction with HashMap values in Java among Integer objects?

    public static HashMap makeHashMap() {
        HashMap<String, Integer> table = new HashMap<String, Integer>();
        table.put("C", 1);
        table.put("V", 2);
        table.put("D", 3);
        table.put("W", 4);
        table.put("E", 5);
        table.put("F", 6);
        table.put("X", 7);
        table.put("G", 8);
        table.put("Y", 9);
        table.put("A", 10);
        table.put("Z", 11);
        table.put("B", 12);
        // System.out.print(table);

        return table;
    }

    public static ArrayList<Object> makeArrayList(HashMap<String, Integer> table) {
        Object[] keys = table.keySet().toArray();
        ArrayList<Object> randomlyGeneratedNotes = new ArrayList<Object>();
        for (int i = 0; i < 83; i++) {
            Object key = keys[new Random().nextInt(keys.length)];
            //  System.out.println(key + " " + table.get(key));
            randomlyGeneratedNotes.add(key);
        }
        System.out.println(randomlyGeneratedNotes);
        return randomlyGeneratedNotes;
    }

    public static void pitchMovement(ArrayList<Object> randomlyGeneratedNotes, HashMap table) {
      Iterator<String> keySetIterator = table.keySet().iterator();
        String key = keySetIterator.next();
        int first = table.get(key);

        for (Object o : randomlyGeneratedNotes) {
            //you want to grab the values of 2 neighboring keys
            if (table.containsKey(o)) {
              //  System.out.println("true");
                Object firstNote=  table.get(key);
                System.out.println(firstNote);
            }
        }
    }
}

How can I perform addition/subtraction between my HashMap values? Or did I use an inappropriate data structure? I tried doing something my pitchMovement method, but the int first = table.get(key); line gives an error of incompatible types:

Object cannot be converted to int.

Not sure if this is a simple error or a more complex one.

I'd like to encourage you to put some learning effort into understanding generics and interfaces. Java will be friendly in its conversion between primitives and value types (like int and Integer ), but plays dumb when dealing with objects of type Object . The problem you're encountering in multiple places is that you're needlessly letting your strongly typed values degrade to type Object .

I'd suggest the following changes:

Change public static HashMap makeHashMap() to public static HashMap<String,Integer> . Otherwise, you'll get back the equivalent of HashMap<Object,Object> , which you don't want.

In public static ArrayList<Object> makeArrayList(HashMap<String, Integer> table) , you're extracting the String typed keys from HashMap, and then converting them to type Object when building your array. Don't change their type-- keep them as String. You may have been thrown by "toArray()" converting to an array of Object values. You can use this technique to preserve the type:

    String[] keys=new String[table.size()];
    keys=table.keySet().toArray(keys);

In doing so, you can easily change the signature of makeArrayList to return an ArrayList of type String :

  public static ArrayList<String> makeArrayList(HashMap<String, Integer> table)

Your pitchMovement signature could be changed to:

  public static void pitchMovement(ArrayList<String> randomlyGeneratedNotes,
                                   HashMap<String,Integer> table)

Note that the specific error you encountered related to HashMap table being defined without generic parameters (which is equivalent to HashMap<Object,Object> ).

When your types haven't been reduced to Object , then Java will use "auto-boxing" to automatically convert between your int and Integer types as needed. The following, for example, is valid.

    Integer x=new Integer(5);
    int y=10+x;
    Integer z=x+y;

In sum, math operations will work as you'd expect without you having to cast and convert between primitives and their equivalent value types, no matter where you store them, but you must take efforts to keep those types preserved wherever you use them.

Try Integer first = table.get(key);

as table is a map of String and Integer, you can get the value as Integer. You can then convert your Integer variable to int.

您需要使用通用参数更新方法签名:

public static void pitchMovement(ArrayList<Object> randomlyGeneratedNotes, HashMap<String, Integer> table)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM