I am having compiler issues with the syntax and want this method to work on the Hashmap object myMap. I need the Add method to take a String value and use the Hashmap put function to add a (key, value) pair.
I tried to put the factory method initiation of newMap inside main and had access issues.
import java.util.*;
public class MyMap {
public static String item;
public static String brand;
Map<String, String> myMap = newMap();
public static void main(String[] args) {
myMap.Add("apple");
}
public static HashMap<String, String> newMap() {
return new HashMap<>();
}
public static void Add(String item) {
String brand = "nobrand";
myMap.put(item, brand);
}
}
compilation error due to static/non static items. I made them all static to make everything accessible throughout the class.
You have two mistakes:
First you should make myMap static like this:
static Map<String, String> myMap = newMap();
Second you should change myMap.Add("apple"); to Add("apple"); because you write a method for main class not for HashMap that you expect to call it like that and also Add method is static and has access to myMap .
Total class would be like this:
import java.util.HashMap;
import java.util.Map;
public class Test {
public static String item;
public static String brand;
static Map<String, String> myMap = newMap();
public static void main(String[] args) {
Add("apple");
}
public static HashMap<String, String> newMap() {
return new HashMap<>();
}
public static void Add(String item) {
String brand = "nobrand";
myMap.put(item, brand);
}
}
I agree with all @Spara answer
I would like to give a little more help
package com.goriant.stackoverflow.answers;
import java.util.HashMap;
import java.util.Map;
public class MyMap {
private static final String DEFAULT_BRAND = "no_brand";
/**
* item - brand Map
*/
private Map<String, String> brandMap;
/**
* constructor
*/
public MyMap() {
this.brandMap = new HashMap<>();
}
/**
* add item with default brand
* @param item
*/
public void addItem(final String item) {
this.brandMap.put(item, DEFAULT_BRAND);
}
/**
* get brand by item
* @param item
* @return brand or null if there is no item in brandMap
*/
public String getBrandByItem(final String item) {
return this.brandMap.get(item);
}
/**
* This is using for testing MyMap class
* @param args
*/
public static void main(String[] args) {
// init MyMap - final is my habit :)
final MyMap myMap = new MyMap();
// add apple with default no_brand
myMap.addItem("apple");
// assert that your brand item is nobrand
assert myMap.getBrandByItem("apple") == DEFAULT_BRAND;
}
}
Revise at 2022-03-01
If you run this class with Java version <14, please pass flag to enable assertion feature
java -ea com.goriant.stackoverflow.answers.MyMap
You can refer github source code here: https://github.com/goriant-com/stackoverflow/blob/master/src/main/java/com/goriant/stackoverflow/answers/MyMap.java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With