You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何在main方法内调用自定义的HashMap生成方法?

调用方案

方案1:将str1改为静态方法,直接调用

main方法是静态方法,无法直接调用非静态的实例方法,最简单的处理方式就是给str1加上static修饰符,完整示例代码如下:

import java.util.HashMap;

public class MapTest {
    // 给原方法加上static修饰
    public static HashMap<String, Integer> str1(String[] strings) {
        HashMap<String, Integer> map = new HashMap<>();
        for (String s : strings) {
            map.put(s, 1);
        }
        return map;
    }

    public static void main(String[] args) {
        // 构造测试用的字符串数组
        String[] testArr = {"a", "b", "c"};
        // 直接调用静态str1方法
        HashMap<String, Integer> result = str1(testArr);
        // 可打印验证返回结果
        System.out.println(result);
    }
}

方案2:保留str1为实例方法,先实例化类再调用

如果你不想把方法改成静态的,就先创建方法所在类的实例对象,再通过对象调用方法:

import java.util.HashMap;

public class MapTest {
    // 保留原方法的非静态定义
    public HashMap<String, Integer> str1(String[] strings) {
        HashMap<String, Integer> map = new HashMap<>();
        for (String s : strings) {
            map.put(s, 1);
        }
        return map;
    }

    public static void main(String[] args) {
        String[] testArr = {"a", "b", "c"};
        // 先实例化类对象
        MapTest mapTest = new MapTest();
        // 通过实例对象调用方法
        HashMap<String, Integer> result = mapTest.str1(testArr);
        System.out.println(result);
    }
}

补充说明

原代码里new HashMap()建议加上泛型写成new HashMap<>(),可以避免编译阶段的泛型擦除警告。

内容的提问来源于stack exchange,提问作者Sbd9933

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:24:01