Why Does This Java Method Appear to Have Two Return Types

Why does this Java method appear to have two return types?

No, you don't have two return types. It's a generic method you are seeing.

  • <E extends Foo> → You are declaring a generic type for your method;
  • List<E> → This is your return type.

Your method can have a generic type E which is a subclass of Foo. The return type of the method is a List<Foo-or-any-subtype-of-Foo>.

Return different type of data from a method in java?

Finally i thought my way is better since when number of return types go higher this kind of a implementation do that in best way.

public static ReturningValues myMethod() {
ReturningValues rv = new ReturningValues();
rv.setValue("value");
rv.setIndex(12);
return rv;
}

Can method return more than one type

A method cannot return more than one type.

The signature of a method contains the return type or void if the method doesn't return anything. Since it must be defined in the method signature, you must return something of that type.

The code

return (true ? null : 0);

is a shorthand if-else statement, or conditional ternary expression, and can be rewritten to this:

if (true) {
return null;
}
else {
return 0;
}

The above code, however, won't compile since one cannot return null if the return type is the primitive type int. The above code will compile, because the JVM will try to convert null to an int, due to auto-unboxing. At runtime, it will throw a NullPointerException, as pointed out by Eran.

In order to 'return multiple types', you could do the following:

public class BooleanOrInt {

private boolean isInteger; // Whether value is boolean or int
private boolean b;
private int i;

public BooleanOrInt(boolean b) {
this.b = b;
this.isInteger = false;
}

public BooleanOrInt(int i) {
this.i = i;
this.isInteger = true;
}

public boolean isInteger() {
return this.isInteger;
}
}

And then your code should be as follows:

BooleanOrInt methodOfA() {
if (someCondition) {
return new BooleanOrInt(theBooleanYouWant);
}
else {
return new BooleanOrInt(theIntegerYouWant);
}
}

How to return 2 values from a Java method?

Instead of returning an array that contains the two values or using a generic Pair class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.

Note: A generic Pair class, as proposed in some of the other answers here, also gives you type safety, but doesn't convey what the result represents.

Example (which doesn't use really meaningful names):

final class MyResult {
private final int first;
private final int second;

public MyResult(int first, int second) {
this.first = first;
this.second = second;
}

public int getFirst() {
return first;
}

public int getSecond() {
return second;
}
}

// ...

public static MyResult something() {
int number1 = 1;
int number2 = 2;

return new MyResult(number1, number2);
}

public static void main(String[] args) {
MyResult result = something();
System.out.println(result.getFirst() + result.getSecond());
}

Can a method have multiple returns of different types?

You can define a custom data type:

public class Result {
private String result1;
private int result2;
// etc.
}

and have your method return an object of this type.

Edit:

Well you can do something like:

public int Nov2()
{
char[] ops = new char[] {'+', '-', '*', '/'};
int i = rand.nextInt(4-0) + 0;
char op1 = ops[i];

int novnum1 = rand.nextInt(101-1) + 1;

int novnum2 = rand.nextInt(101-1) + 1;

int result = 0;

switch(op1) {
case '+': result = novnum1 + novnum2; break;
case '-': result = novnum1 - novnum2; break;
case '*': result = novnum1 * novnum2; break;
case '/': result = novnum1 / novnum2; break;
}

String nov2Exp = novnum1 + " " + op1 + " " + novnum2 + " = ";

setContentView(R.layout.gameview);

TextView display = (TextView) findViewById(R.id.exp);

display.setText(nov2Exp);

return result;
}

This method will generate you a new expression, put it on the screen and then return the result. You can store it somewhere and when the user clicks the button compare it with his input.

When two interfaces have conflicting return types, why does one method become default?

It's not a default method you provide but a bridging method. In the parent interface you have defined.

public BarInterface getBar();

and you must have a method which can be called which implements this.

e.g.

FooInterface fi = new Foo();
BarInterface bi = fi.getBar(); // calls BarInterface getBar()

However, you also need to be able to call it's co-variant return type.

FooInterface2 fi = new Foo();
Bar bar = fi.getBar(); // calls Bar getBar()

These are the same method, only difference is that one calls the other and cast the return value. It's the method which appears to have a default implementation as it is on the interface which does this.

Note: if you have multiple levels of interfaces/class and each has a different return type, the number of methods accumulates.

The reason it does this is that the JVM allows having multiple methods with different return type because the return type is part of the signature. I'e the caller has to state which return type it is expecting and the JVM doesn't actually understand co-variant return types.

Java, what if I want to return different types from function?

You can't return multiple types but you can redesign so you don't have to. Some possibilities:

  1. Don't return an error message. Throw or rethrow an exception instead and let the caller handle it.
  2. Create some class that can encapsulate a success and error state and all related info, return an instance of that.

I recommend option 1. You're already handling an exception, you can see its use for it error handling. No reason to stop it in its tracks there, handle any local cleanup then keep it going up to the caller.


Some hastily constructed examples now that I'm back at a keyboard, intended only to illustrate concepts, not to be exhaustive or necessarily used verbatim:

Cleanup then rethrow:

public boolean test () throws javax.script.ScriptException {
try {
transaction.begin();
...
transaction.commit();
return true;
} catch (javax.script.ScriptException ex) {
transaction.rollback();
throw ex;
}
}

Clean up then rethrow a different exception type if needed:

public boolean test () throws MyGreatException {
try {
transaction.begin();
...
transaction.commit();
return true;
} catch (javax.script.ScriptException ex) {
transaction.rollback();
throw new MyGreatException(ex);
}
}

Return an object that provides status information (this is just a quick example of the general idea):

public class TransactionResult {

private final boolean failed;
private final String reason;

/** Construct a result that represents a successful transaction. */
public TransactionResult () {
failed = false;
reason = null;
}

/** Construct a result that represents a failed transaction with a reason. */
public TransactionResult (String failedReason) {
failed = true;
reason = failedReason;
}

public boolean isFailed () {
return failed;
}

public String getReason () {
return reason;
}

}

And then:

public TransactionResult test () {
TransactionResult result;
try {
transaction.begin();
...
transaction.commit();
result = new TransactionResult();
} catch (javax.script.ScriptException ex) {
transaction.rollback();
result = new TransactionResult(ex.getMessage());
}
return result;
}

Etc.



Related Topics



Leave a reply



Submit