简体   繁体   English

原始类和原始数据类型之间有什么区别?

[英]What is the difference between a primitive class and primitive data type?

I am reading a book on Java, and they seem to use the two terms "primitive class" and "primitive data type" interchangeably. 我正在读一本关于Java的书,他们似乎可以互换地使用“原始类”和“原始数据类型”这两个术语。

What's the difference between the two? 这两者有什么区别? I understand that Integer is a wrapper class, and people reference int as a primitive data type. 我知道Integer是一个包装类,人们将int引用为原始数据类型。 So is it also a primitive class? 它也是一个原始类吗?

They're confusing their vernacular here. 他们在这里混淆了他们的白话。

A primitive is a data type which is not an object. 基元是不是对象的数据类型。 int , float , double , long , short , boolean and char are examples of primitive data types. intfloatdoublelongshortbooleanchar是原始数据类型的示例。 You can't invoke methods on these data types and they don't have a high memory footprint, which is their striking difference from classes. 您不能在这些数据类型上调用方法,并且它们没有高内存占用,这是它们与类的显着区别。

Everything else is a class (or class-like in the case of interfaces and enums). 其他所有东西都是一个类(或者在接口和枚举的情况下类似于类)。 Pretty much everything that begins with an upper-case letter, like String , Integer are classes. 几乎所有以大写字母开头的内容,如StringInteger都是类。 Arrays also classify as not-primitives, even though they may hold them. 数组也可以归类为非原语,即使它们可以保留它们。 int[] isn't a primitive type but it holds primitives. int[]不是基本类型,但它包含基元。

The only thing that could realistically come close would be the wrapper classes, as explained by the JLS , but even then, they're still classes, and not primitives. 实际上唯一可以接近的是封装类, 如JLS所解释的那样 ,但即便如此,它们仍然是类,而不是原语。

Primitive class has a special meaning in the context of reflection APIs: when you need to retrieve a method that takes a parameter of primitive type, you need a primitive class object that corresponds to that primitive type. 原始类在反射API的上下文中具有特殊含义:当您需要检索采用基本类型参​​数的方法时,您需要一个与该基本类型对应的基本类对象。

This is important if you must distinguish between overloads that take primitives and overloads that take wrappers: 如果必须区分采用原语的重载和采用包装器的重载,这一点很重要:

void someMethod(int n);
void someMethod(Integer n);

There are two ways to obtain this class object: 有两种方法可以获取此类对象:

  • Using class literal, eg int.class , or 使用类文字,例如int.class ,或
  • Using TYPE member of the corresponding wrapper class, eg Integer.TYPE . 使用相应包装类的TYPE成员,例如Integer.TYPE

This is not the same class as the class representing the primitive wrapper. 这与表示原始包装器的类不是同一个类。 In other words, 换一种说法,

int.class != Integer.class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM