Double vs double in java [duplicate]

2020-01-29 10:27发布

Possible Duplicate:
Java : different double and Double in comparison

In a sample java program for one of my labs, I have two different methods taking Double and double parameters respectively.
How do I differentiate between them when passing arguments to them?

7条回答
放我归山
2楼-- · 2020-01-29 10:37

First off you need to understand the difference between the two types. double is a primitive type whereas Double is an Object.

The code below shows an overloaded method, which I assume is similar to your lab code.

void doStuff(Double d){ System.out.println("Object call"); }
void doStuff(double d){ System.out.println("Primitive call"); }

There are several ways you can call these methods:

doStuff(100);
doStuff(200d);
doStuff(new Double(100));

These calls will result in:

"Primitive call"
"Primitive call"
"Object call"
查看更多
爷、活的狠高调
3楼-- · 2020-01-29 10:51
// Method A
public static void foo(Double d) {...}

// Method B 
public static void foo(double d) {...}

Evidently, if you pass a Double object then Method A will be called; i.e. if you had something like:

Double d = new Double(1.0);

Further, if you pass a double literal you will call Method B. What's interesting is if you have something like

double d = new Double(1.0);

In this case Method B will also be called, because the type of d is double; the Double object gets unboxed to a double. On the same note, if you had:

Double d = 1.0;

then Method A would be called, because the type of d would be Double (the double-literal gets autoboxed to a Double).

查看更多
\"骚年 ilove
4楼-- · 2020-01-29 10:52

What you have is an example of method overloading. The good part is that the compiler and the JVM will select the correct method automatically based on the type of the arguments that is used when you call the method.

查看更多
迷人小祖宗
5楼-- · 2020-01-29 10:52

Double is a wrapper class while double is a primitive type like c/c++. As pointed out above, Double is mostly used in generics but also is useful anywhere there is a need for both numerical value and proper object encapsulation. In most cases the Double and double can be used interchangeably.

查看更多
狗以群分
6楼-- · 2020-01-29 10:54

Double parameter can be null when double can't.

查看更多
Root(大扎)
7楼-- · 2020-01-29 10:54

Double is reference type and double is value type.

The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double." link

As @Fess mentioned and because Double is reference type it can be null.

If you want you can explictly convert from Double to double with .doubleValue() method and viceverrsa with new Double(1.0).

Also as @millimoose said:

You should use X.valueOf() instead of new X(). The valueOf methods are allowed to cache the boxing types to reduce memory use. (Not sure this is done for Doubles but it's a good habit to get into.)"

查看更多
登录 后发表回答