1

I came across this code:

sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);

and the method registerListener() returnes a boolean value ( http://developer.android.com/reference/android/hardware/SensorManager.html#registerListener(android.hardware.SensorEventListener,android.hardware.Sensor,int,android.os.Handler) , though this code uses it like it returnes nothing.

How is that possible?

4

3 回答 3

2

You don't have to use the value returned by registerListener().

Consider this code:

void performOperation() {
    doSomething(); 
}

doSomething does something and returns true if the operation was successfully done, false otherwise.
performOperation doesn't return a thing, it simply performs the operation.

Another example:

public boolean delete():

Returns: true if and only if the file or directory is successfully deleted; false otherwise

You don't have to use the value returned by delete method (but it's highly recommended to).


Clarification:

You're probably confused with method signature in this situation.

Methods are declared like:

modifier return-type name(parameters ..)

When your method declared to return something, it must return something! But if you use it within another method that returns nothing (void), then you're not forced to use this value.

于 2013-07-14T09:06:19.887 回答
0

Java does not force you to assign the values of expressions to variables, including method calls. There are quite a few examples of this in the standard library - for example, Map.put returns the previous value associated with a key, which can be useful but is often ignored.

Map<String, String> map = new HashMap<String, String>();
map.put("a", "1"); // Ignoring the returned value
String previousValue = map.put("a", "2"); // Assigning the returned value ("1") to a new variable

Related aside: you can even ignore new instances of objects returned by new (but there is probably no good use case for doing this):

new HashMap<String, String>();
于 2013-07-14T09:08:28.020 回答
0

In Java, every expression can be made into a statement by adding a semicolon. The value computed by the expression is ignored.

This isn't restricted to method call expressions; the following is also valid.

int a=2;
a + 40;  // compute 42, don't store

You probably do this more than you think. Assignment to a variable is also an expression, the value of which is usually thrown away. Very rarely you see code like this:

int b = (a = 56); // store result of assignment
于 2013-07-14T09:08:31.107 回答