HashMap可以包含键/值的自定义类吗? [英] Can HashMap contain custom class for key/value?

查看:103
本文介绍了HashMap可以包含键/值的自定义类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在HashMap< K V >中,可以将 K V 用作自定义类对象,而不是包装器类对象?

In HashMap<K,V>, can K or V be custom class object instead of wrapper class objects??

import java.util.HashMap;
import java.util.Map;

public class Test {

    public static void main(String[] args) {
        Test test=new Test();       
        HashMap<String, test> a= new HashMap<String, test>();
    }
}

发生错误:测试无法解析为一种类型.

Error occurs: test cannot be resolved to a type.

先谢谢了.问候.

推荐答案

在hashmap中,可以将自定义类型作为键/值对包含.

In hashmap, yes you can include custom types as Key/Value pair.

但这不应该是 object ,它必须明确地是 type .

but that should not be object , it must of clearly a type .

表示一个 class ,您可以提及它成为自定义类型的 type .

means a class you can mention which becomes type for custom types.

示例

您可以将String类型变量定义为 String s ="abc";

you can define String type variable as String s = "abc";

现在如果我们尝试像下面这样写

now if we try to write like below

HashMap<String, s> a= new HashMap<String, s>();

它不会编译为's 的类型,而不是 String 类型的对象,

it wont compile as 's' is not the type rather than its an object of type String,

因此它应该变成下面的样子

hence it should become like below

HashMap<String, String> a= new HashMap<String, String>();

所以您的代码如下

Test test=new Test();       
        HashMap<String, test> a= new HashMap<String, test>();

应该成为

Test test=new Test();       
        HashMap<String, Test> a= new HashMap<String, Test>();

这篇关于HashMap可以包含键/值的自定义类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆