1

I know how to "setValue" the "getValue" however how you do "getValue" in this case?

public void setInfo(String name, int age) {
    setName(name);
    setAge(age);
}

Is there a way to getInfo with string and int at the same time?

Vic
  • 21,473
  • 11
  • 76
  • 97
Claudio Lopez
  • 131
  • 1
  • 3
  • 10

5 Answers5

3

As per code , what I assume that both name and age are part of the InfoObject, so you can return the whole object in getInfo() call, ex-

public InfoObject getInfo() {
    return infoObject();
}

Because you can not return two values from same function. If you don't want to use this way, In that case you have to write two seperate methods for name and age each. like:

public String getName() {
    return this.name;
}

and

public int getAge() {
    return this.age;
}

This way you can make your code clean and understandable.

Andreas
  • 154,647
  • 11
  • 152
  • 247
pbajpai
  • 1,303
  • 1
  • 9
  • 24
1

In some programming language such as swift ,there is "tuple" can return with two value at the same time.

However in the Java world you there is no official "tuple", but you can do something similar:

public class Pair<F, S> {
    public F first;
    public S second;
}

in your case:

Pair<String, Integer> mValue;

public void setInfo(String name, int age) {
    mValue = new Pair<String, Integer>(name, age);
}

public Pair<String, Integer> getInfo() {
    return mValue;
}
Chaobin Wu
  • 29
  • 1
0

You may try the following method:

public Object[] getValue(){
    return new Object[]{getName(), getAge()};
}

Hope, you already have methods like getName() and getAge() as you have setName(String name) and setAge(int age).

Sanjeev Saha
  • 2,632
  • 1
  • 12
  • 19
-1

There are multiple ways, one is given below:

public Object[] getInfo() {
    Object[] info = new Object[2];
    info[0] = getName();
    info[1] = getAge();
    return info;
}
Azodious
  • 13,752
  • 1
  • 36
  • 71
  • That will lose compiler type-checking. – Andreas Jun 14 '16 at 04:47
  • 1
    I agree with @Andreas, You have to cast the result before using that, apart from that In my opinion, its not a good way of exposing the API to provide information to the other classes which will use this method. This API may little confusing to the other classes which are going to use it. – pbajpai Jun 14 '16 at 04:52
-1

I usually use java.util.Map when i need to do that, for example:

private Map<String, Object> getInfo() {
    Map<String, Object> result;
    result.put("name", name);
    result.put("age", age);
    return result;
}

https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html