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

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

问题描述

Java集合只存储对象,而不是基本类型;

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

推荐答案

p>这是一个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的支持。 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.

拳击是一种技术上的妥协,我觉得是实施细节泄漏到语言中。自动装箱是很好的语法糖,但仍然是性能的惩罚。如果有什么,我想编译器警告我,当它autoboxes。

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天全站免登陆