括号围绕数据类型? [英] Parentheses around data type?

查看:130
本文介绍了括号围绕数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名初学程序员并在我的教科书中遇到过这个问题:

I am a beginning programmer and came across this in my textbook:

public boolean equals(DataElement otherElement)
{
    IntElement temp = (IntElement) otherElement;            
    return (num == temp.num);
}

IntElement 是一个 DataElement 的子类。 num 是一个存储链表值的int。

IntElement is a subclass of DataElement. num is an int storing a value for a linked list.

(IntElement)在 temp =? IntElement temp = otherElement 之后会出现什么问题? ?而且,一般来说,将数据类型放在括号中的是什么呢?

What is the purpose of (IntElement) after temp =? What would be wrong with IntElement temp = otherElement? And, in general, what does putting a data type in parentheses like that do?

推荐答案

这称为铸造,请参见此处:

This is called casting, see here:

  • http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

基本上,通过这样做:

IntElement temp = (IntElement) otherElement;  

您告诉编译器忽略您声明的事实 otherElement as DataElement 并相信你将是 IntElement 而不是 DataElement DataElement 的其他一些子类。

you are telling compiler to ignore the fact you declared otherElement as DataElement and trust you it is going to be an IntElement and not DataElement or some other subclass of DataElement.

你不能只做 IntElement temp = otherElement; 这样你就可以生成 otherElement ,它被定义为 DataElement 成为其他元素,在本例中为 IntElement 。这将是类型安全的一大打击,这就是首先定义类型的原因。

You cannot do just IntElement temp = otherElement; as this way you would make otherElement, which was defined as DataElement become some other element, in this case IntElement. This will be a big blow to type-safety, which is the reason types are defined at the first place.

技术上可以使用类型推断来完成:

This could technically be done using type inference:

  • http://en.wikipedia.org/wiki/Type_inference

但Java不支持,你必须明确。

however Java does not support that and you have to be explicit.

如果可以获取其他元素,您可能希望在转换之前使用 instanceof 来检查类型运行时:

If it's possible to get other elements, you may want to use instanceof to check the type runtime before casting:


  • Operators / TheinstanceofKeyword.htm> http://www.java2s.com/Tutorial/Java/0060_Operators/TheinstanceofKeyword.htm

在您完成此操作后的某个时刻,您可能也想看看泛型:

At some point after you go through this, you might want to take a look at generics, too:

  • http://en.wikipedia.org/wiki/Generics_in_Java

这篇关于括号围绕数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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