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?
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?
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.
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;
}
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)
.
There are multiple ways, one is given below:
public Object[] getInfo() {
Object[] info = new Object[2];
info[0] = getName();
info[1] = getAge();
return info;
}
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