Hashmap syntax error on tokens in java

I use the opencript IDE, I get the error message "Syntax error on tokens, deletes these tokens" my code

import java.util.Map; public class HTMLObjectMap { HashMap<String, String> params = new HashMap<String, String>(); params.put("test","test"); } 
+4
source share
4 answers

Statement

 params.put("test","test"); 

must be inside a method that you did not define. I.e

 public class HTMLObjectMap { HashMap<String, String> params = new HashMap<String, String>(); public void method() { params.put("test","test"); } } 

Or maybe you want an initializer, as in

 public class HTMLObjectMap { HashMap<String, String> params = new HashMap<String, String>(); { params.put("test","test"); } } 
+7
source

You need to enter the initialization code in braces:

 public class HTMLObjectMap { HashMap<String, String> params = new HashMap<String, String>(); { params.put("test","test"); } } 

or if you need it:

 public class HTMLObjectMap { static HashMap<String, String> params = new HashMap<String, String>(); static { params.put("test","test"); } } 
+1
source

I think you should make your map private, it will not violate the encapsulation method, getter and setter to access and insert the value outside.

 public class HTMLObjectMap { private HashMap<String, String> params = new HashMap<String, String>(); { // initialize if required } public void get(String key){ params.get(key); } public String put(String key,String value){ params.put(key,value); } } 
+1
source

You must initialize the class. The java class has only variables and methods. inside a class, you can declare variables or define methods, no matter what you want, which means you need to define methods.

 public class HTMLObjectMap { HashMap<String, String> params = new HashMap<String, String>(); // this is objects method. { params.put("test","test"); } // this is your own method private void method1(){ params.put("test1","test1"); } } 
+1
source

All Articles