简体   繁体   English

初始化对象并将对象放入HashMap的不同方法

[英]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. 我一直在玩HashMaps,并意识到在没有main()的类中实例化具有main()的类中的实例化HashMaps的行为会有所不同。

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 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()? 在没有main()的类中初始化HashMap的正确方法是什么?

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

This code is not in a method or in a static block. 该代码不在方法或static块中。 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. Main就像其他方法一样,只是一个void(方法),只是它首先执行。 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). 如果您想像这样将您的代码放入void或任何其他返回任何类型的方法(可以是静态或实例-没关系)。

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: 您还可以返回您的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 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 . 之后,只需一步,就可以学习Java语言

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. 我认为您的问题是,您正在抽象类中实例化HashMap,使该类成为非抽象类或对其进行子类化,并且错误应消失。 I have used Hashmaps in many classed and never had an issue with them, here is the definition of a abstract class from Oracle, 我在许多分类中都使用过Hashmap,但从未遇到过问题,这是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());
     }};}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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