`

在Java中使用generic arguments时的基本问题

阅读更多

      问题怎么来的?

      在编码时,声明一个HashMap类型的变量时,在generic arguments部分将Integer写为了int,像下面这样:

HashMap<int, String> var;

      未等编译,IDE已经给出了提示,有问题。


      问题原因:Java中,在generic arguments不能使用基本数据类型,比如int等。


      对这个问题的回答,可以看看下面这个web:

      http://stackoverflow.com/questions/1780385/java-hashmapstring-int-not-working

      其中,回答者cletus,还就auto-boxing/unboxing进行说明了。下面是其回答的原文:

         You can't use primitive types as generic arguments in Java. Use instead:

        Map<String, Integer> myMap = new HashMap<String, Integer>();

        With auto-boxing/unboxing there is little difference in the code. Auto-boxing means you can write:

        myMap.put("foo", 3);

        instead of:

        myMap.put("foo", new Integer(3));

        Auto-boxing means the first version is implicitly converted to the second. Auto-unboxing means you can write:

        int i = myMap.get("foo");

        instead of:

        int i = myMap.get("foo").intValue();

        The implicit call to intValue() means if the key isn't found it will generate a NullPointerException, for example:

        int i = myMap.get("bar"); // NullPointerException

        The reason is type erasure. Unlike, say, in C# generic types aren't retained at runtime. They are just "syntactic sugar" for explicit casting to save you doing this:

        Integer i = (Integer)myMap.get("foo");

        To give you an example, this code is perfectly legal:

        Map<String, Integer> myMap = new HashMap<String, Integer>();
        Map<Integer, String> map2 = (Map<Integer, String>)myMap;
        map2.put(3, "foo");


      另外,附上一篇关于Java generics的文章,它的内容以及附录的参考资料,有帮助。

      多角度看 Java 中的泛型

分享到:
评论

相关推荐

    java开发工具Gel帮助文档

    **Java开发工具 Gel 帮助文档** 在Java开发领域,高效、实用的工具是提升开发者生产力的关键。Gel(Generic Eclipse Launcher)就是这样一款工具,它作为Eclipse平台...Gel的使用将使你在Java开发过程中更加得心应手。

    YuiCompressor2.4.8

    在本文中,我们将详细探讨YuiCompressor的功能、工作原理以及如何在WebStorm中使用它。 ### 一、YuiCompressor的功能 1. **压缩代码**:YuiCompressor的主要任务是对JavaScript和CSS文件进行压缩,通过删除空格、...

    websphere加快部署服务器启动速度

    在Websphere管理控制台中,进入`Servers` -&gt; `Server Types` -&gt; `WebSphere application servers` -&gt; `server1` -&gt; `Server Infrastructure` -&gt; `Java and Process Management` -&gt; `Process Definition` -&gt; `Java ...

    webstorm_phpstorm_yuicompressor-2.4.8.jar

    在开发Web应用程序时,为了提高页面加载速度,减少网络传输的数据量,对JavaScript和CSS进行压缩是必不可少的步骤。Yahoo! Compressor(简称YUI Compressor)是一款强大的代码压缩工具,它可以有效地减小JS和CSS文件...

    JDK 1.5的泛型實現(Generics in JDK 1.5)

    generic classes,所以製造元素時必須使用泛型語 法(角括號)。請與圖 2b比較。 圖 6和圖 7的泛型語法自 JDK1.3+GJ以來不曾改變過。它迥異於 C++,後者要求 程式必須在 class名稱前加上語彙單元 template,...

    jdk1.8_win32.rar

    - With type inference, the compiler can often determine the type arguments for creating instances of generic classes, reducing the need for explicit type specifications. 7. **Enhanced Compiler** - ...

    获取规范货币类型UDF函数.doc

    在大数据处理领域,特别是金融数据分析场景中,经常需要对数据进行标准化处理。对于货币类型的规范化处理是常见需求之一。本篇文章将详细介绍如何创建一个Hive UDF(User Defined Function)来实现获取规范货币类型...

    jdk1.8-windows版64位

    7. **Type Inference for Generic Instance Creation (Diamond Operator):** With JDK 1.8, you can omit type arguments when creating generic objects using the diamond operator `&lt;&gt;`. The compiler infers the...

    was部署应用方法.docx

    在本文中,我们将详细介绍 WAS 服务器部署应用的方法,包括配置 WAS 环境变量、建立虚拟主机、建立应用服务、配置 JVM 参数等步骤。 配置 WAS 环境变量 在部署 WAS 应用之前,需要配置好 WAS 的环境变量。.Export ...

    play框架手册

    更多公共类型generic typing问题 - 77 - 08.Play.libs库包 - 78 - 用XPath解析XML - 78 - Web Service client - 79 - Functional programming with Java功能扩展? - 79 - Option, Some&lt;T&gt; and None&lt;T&gt; - 80 - Tuple...

    c# 语言 概述

    4. 泛型(generic):允许在类、接口和方法中使用类型参数,提高代码的复用性。 5. 构造函数与析构函数:构造函数用于初始化新创建的对象,而析构函数则在对象销毁前执行清理工作。 6. 装箱与拆箱:值类型到引用...

    Addison.Wesley.C++.by.Dissection.2002.pdf

    - **C++ Compared with Java:** Compares C++ with Java, highlighting differences in syntax and features. ### Chapter 2: Native Types and Statements Chapter 2 delves deeper into the native types and ...

    Packt.Mastering.Csharp.and.NET.Programming

    - **.NET as a Reaction to the Java World**: Microsoft’s response to Sun Microsystems’ Java platform, aiming to provide a robust framework for building and running applications. - **The Open Source...

    spring-boot-reference.pdf

    23.7. Accessing Application Arguments 23.8. Using the ApplicationRunner or CommandLineRunner 23.9. Application Exit 23.10. Admin Features 24. Externalized Configuration 24.1. Configuring Random Values...

    python3.6.5参考手册 chm

    Python参考手册,官方正式版参考手册,chm版。以下摘取部分内容:Navigation index modules | next | Python » 3.6.5 Documentation » Python Documentation contents What’s New in Python ...

    Python程序设计(第二版).chm

    PyTree: A Generic Tree Object Viewer Chapter 18. Text and Language Section 18.1. "See Jack Hack. Hack, Jack, Hack" Section 18.2. Strategies for Parsing Text in Python Section 18.3. String ...

    Object-Oriented Software Construction 2nd

    10.3 GENERIC CLASSES 320CONTENTS xx 10.4 ARRAYS 325 10.5 THE COST OF GENERICITY 328 10.6 DISCUSSION: NOT DONE YET 329 10.7 KEY CONCEPTS INTRODUCED IN THIS CHAPTER 329 10.8 BIBLIOGRAPHICAL NOTES 330 ...

Global site tag (gtag.js) - Google Analytics