为什么 Java Collections 不能直接存储 Primitives 类型? [英] Why can Java Collections not directly store Primitives types?

查看:20
本文介绍了为什么 Java Collections 不能直接存储 Primitives 类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 集合只存储对象,不存储原始类型;但是我们可以存储包装类.

Java collections only store Objects, not primitive types; however we can store the wrapper classes.

为什么会有这个限制?

推荐答案

这是一个 Java 设计决策,有些人认为这是一个错误.容器需要对象,而原语不是从对象派生的.

It was a Java design decision, and one that some consider a mistake. Containers want Objects and primitives don't derive from Object.

这是 .NET 设计人员从 JVM 中学到的一个地方,并实现了值类型和泛型,从而在许多情况下消除了装箱.在 CLR 中,泛型容器可以将值类型存储为底层容器结构的一部分.

This is one place that .NET designers learned from the JVM and implemented value types and generics such that boxing is eliminated in many cases. In CLR, generic containers can store value types as part of the underlying container structure.

Java 选择在没有 JVM 支持的情况下在编译器中添加 100% 的通用支持.JVM 不支持非对象"对象.Java 泛型允许您假装没有包装器,但您仍然要为拳击的性能付出代价.这对于某些类别的程序很重要.

Java opted to add generic support 100% in the compiler without support from the JVM. The JVM being what it is, doesn't support a "non-object" object. Java generics allow you to pretend there is no wrapper, but you still pay the performance price of boxing. This is IMPORTANT for certain classes of programs.

装箱是一种技术上的妥协,我觉得这是泄漏到语言中的实现细节.自动装箱是一种很好的语法糖,但仍然是一种性能损失.如果有的话,我希望编译器在自动装箱时警告我.(据我所知,现在可能,我在 2010 年写了这个答案).

Boxing is a technical compromise, and I feel it is implementation detail leaking into the language. Autoboxing is nice syntactic sugar, but is still a performance penalty. If anything, I'd like the compiler to warn me when it autoboxes. (For all I know, it may now, I wrote this answer in 2010).

关于拳击的一个很好的解释:为什么有些语言需要装箱和拆箱?

A good explanation on SO about boxing: Why do some languages need Boxing and Unboxing?

对 Java 泛型的批评:为什么有人声称 Java 的泛型实现很糟糕吗?

And criticism of Java generics: Why do some claim that Java's implementation of generics is bad?

在 Java 的辩护中,很容易回顾和批评.JVM 经受住了时间的考验,在很多方面都是一个很好的设计.

In Java's defense, it is easy to look backwards and criticize. The JVM has withstood the test of time, and is a good design in many respects.

这篇关于为什么 Java Collections 不能直接存储 Primitives 类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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