简体   繁体   中英

Different ways to initialize and put objects to HashMaps

I've been playing around with HashMaps and realized that instantiating HashMaps in a class that has main() behaves differently when instantiated in a class that doesn't have main.

Demo.java

import java.util.HashMap;

public class Demo {

public static void main(String args[]) {
        System.out.println(new Circle());

        HashMap<String, Object> shapes = new HashMap<String,Object>();
        shapes.put("Circle", new Circle());
    }
}

GeometricObject.java

import java.util.HashMap;

abstract class GeometricObject
{   
    HashMap<String, Object> shapes = new HashMap<String,Object>(); //error
    shapes.put("Circle", new Circle()); //error
}

What is a correct way to initialize a HashMap in a class that doesn't have a main()?

shapes.put("circle", new Circle());

This code is not in a method or in a static block. This code can not be executed freely in the body of a class. This will cause a compilation error.

Initialization block:

abstract class GeometricObject
{  
    HashMap<String, Object> shapes = new HashMap<String,Object>();
    {
        shapes.put("Circle", new Circle());
    }
}

Main is simply a void (method), just like any other, except it's executed as first. If you want to put your code like this put it inside void or any other method returning any type (may be static or instance - doesn't matter).

public void noReturn(){
          HashMap<String, Object> shapes = new HashMap<String,Object>(); 
            shapes.put("Circle", new Circle()); 
    }

public int returnsInt(){
          HashMap<String, Object> shapes = new HashMap<String,Object>();
            shapes.put("Circle", new Circle());
            return 1;
    }

You can also return your HashMap:

public Map returnNewMap(){
          HashMap<String, Object> shapes = new HashMap<String,Object>();
            shapes.put("Circle", new Circle());
            return shapes; //here's your HashMap returned
    }

This is one way to do what you want but not the only one.

GeometricObject.java

import java.util.HashMap;

class GeometricObject
{   
    public static HashMap<String, Object> giveMeNewShapesDude() {
        HashMap<String, Object> shapes = new HashMap<String,Object>();
        shapes.put("Circle-1", new Circle());
        shapes.put("Circle-2", new Circle());
        shapes.put("Circle-3", new Circle());
        return shapes;
    }
}

Demo.java

import java.util.HashMap;

public class Demo {

    public static void main(String args[]) {    
        HashMap<String, Object> shapes = GeometricObject.giveMeNewShapesDude();
        system.out.println("Shapes : " + shapes);
    }
}

Only one step to do after this, learn the Java language .

You may use double brace initialization like so:

Map<String,Object> map = new HashMap<String,Object>() {
 {
    put("circle", new Circle());
 }
};

I think you issue is you are instantiating the HashMap inside an abstract class, make the class non-abstract or subclass it and the error should go away. I have used Hashmaps in many classed and never had an issue with them, here is the definition of a abstract class from Oracle,

Abstract Classes Compared to Interfaces

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods. With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.

import java.util.HashMap;

abstract class GeometricObject
{   
     HashMap<String, Object> shapes;
     {shapes = new HashMap<String,Object>(){{
         put("Circle", new Circle());
         put("Square", new Square());
     }};}
}

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