0

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()?

roeygol
  • 4,908
  • 9
  • 51
  • 88
apebeast
  • 368
  • 3
  • 15
  • your code 'GeometricObject.java' is not in the method. which is incorrect – Naresh Vavilala Jan 30 '15 at 23:37
  • 1
    Wow! In a very short time 8 answers to a question of imho questionable quality. I was (and still am) confused because of your comment `//error` (the first one). Because deleting the `shapes.put ...` line will certainly give you a syntactically correct answer ... – Hille Jan 30 '15 at 23:57

7 Answers7

2
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.

christopher
  • 26,815
  • 5
  • 55
  • 89
1

Initialization block:

abstract class GeometricObject
{  
    HashMap<String, Object> shapes = new HashMap<String,Object>();
    {
        shapes.put("Circle", new Circle());
    }
}
baju
  • 511
  • 5
  • 19
  • Upvoting as actually trying out the code speaks in your favor ... ending up with `new Object()` ... :-) – Hille Jan 31 '15 at 00:05
  • @Hille `new Object()` :) - nice catch – baju Jan 31 '15 at 00:09
  • I've tried this variation before, but I still don't get the difference between single brace and double brace. – apebeast Jan 31 '15 at 00:16
  • Double brace: [click](http://stackoverflow.com/questions/1958636/what-is-double-brace-initialization-in-java) Initlization block [click](http://stackoverflow.com/questions/19058766/java-initialization-order) – baju Jan 31 '15 at 00:19
0

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
    }
RichardK
  • 3,228
  • 5
  • 32
  • 52
0

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.

Mason
  • 393
  • 7
  • 22
-1

You may use double brace initialization like so:

Map<String,Object> map = new HashMap<String,Object>() {
 {
    put("circle", new Circle());
 }
};
Ogen
  • 6,499
  • 7
  • 58
  • 124
  • 2
    Please check [click](http://blog.jooq.org/2014/12/08/dont-be-clever-the-double-curly-braces-anti-pattern/) - it is generally not really good idea – baju Jan 30 '15 at 23:46
  • I think it would be fine for his use-case – Ogen Jan 30 '15 at 23:51
  • 1
    I do not claim that in each case it is bad idea. I provide link just to raise awareness what such construction really means. – baju Jan 30 '15 at 23:55
-1

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.

faljbour
  • 1,367
  • 2
  • 8
  • 15
-2
import java.util.HashMap;

abstract class GeometricObject
{   
     HashMap<String, Object> shapes;
     {shapes = new HashMap<String,Object>(){{
         put("Circle", new Circle());
         put("Square", new Square());
     }};}
}
SteveL
  • 3,331
  • 4
  • 32
  • 57