从java中的方法返回不同类型的数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18140964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return different type of data from a method in java?
提问by Ruchira Gayan Ranaweera
public static void main(String args[]) {
myMethod(); // i am calling static method from main()
}
.
.
public static ? myMethod(){ // ? = what should be the return type
return value;// is String
return index;// is int
}
myMethod()
will return String and int value. So take these returning values from main()
i came up with following solution.
myMethod()
将返回 String 和 int 值。因此,从main()
我那里获取这些返回值想出了以下解决方案。
create a class call ReturningValues
创建类调用 ReturningValues
public class ReturningValues {
private String value;
private int index;
// getters and setters here
}
and change myMethod()
as follows.
并更改myMethod()
如下。
public static ReturningValues myMethod() {
ReturningValues rv = new ReturningValues();
rv.setValue("value");
rv.setIndex(12);
return rv;
}
Now my question,is there any easier way to achieve this??
现在我的问题是,有没有更简单的方法来实现这一目标?
采纳答案by Ruchira Gayan Ranaweera
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;
}
回答by chrylis -cautiouslyoptimistic-
No. Java methods can only return one result (void
, a primitive, or an object), and creating a struct
-type class like this is exactly how you do it.
不可以。Java 方法只能返回一个结果(void
、原语或对象),而创建这样的struct
-type 类正是您这样做的方式。
As a note, it is frequently possible to make classes like your ReturningValues
immutable like this:
需要注意的是,经常可以像这样创建ReturningValues
不可变的类:
public class ReturningValues {
public final String value;
public final int index;
public ReturningValues(String value, int index) {
this.value = value;
this.index = index;
}
}
This has the advantage that a ReturningValues
can be passed around, such as between threads, with no concerns about accidentally getting things out of sync.
这样做的优点是ReturningValues
可以传递a ,例如在线程之间传递,而不必担心意外使事物不同步。
回答by Narendra Pathai
This can be one of the solution. But your present solution is good enough. You can also add new variables and still keep it clean, which cannot be done with present code.
这可以是解决方案之一。但是您目前的解决方案已经足够好了。您还可以添加新变量并保持干净,这是现有代码无法做到的。
private static final int INDEX_OF_STRING_PARAM = 0;
private static final int INDEX_OF_INT_PARAM = 1;
public static Object[] myMethod() {
Object[] values = new Object[2];
values[INDEX_OF_STRING_PARAM] = "value";
values[INDEX_OF_INT_PARAM] = 12;
return values;
}
回答by Ankur Shanbhag
Generally if you are not sure of what value you will end up returning, you should consider using return-type as super-class of all the return values. In this case, where you need to return String or int, consider returning Object class(which is the base class of all the classes defined in java).
通常,如果您不确定最终会返回什么值,您应该考虑使用 return-type 作为所有返回值的超类。在这种情况下,您需要返回 String 或 int,请考虑返回 Object 类(它是 java 中定义的所有类的基类)。
But be careful to have instanceof checkswhere you are calling this method. Or else you may end up getting ClassCastException.
但是要小心对调用此方法的位置进行instanceof 检查。否则你最终可能会得到ClassCastException。
public static void main(String args[]) {
Object obj = myMethod(); // i am calling static method from main() which return Object
if(obj instanceof String){
// Do something
}else(obj instance of Integer) {
//do something else
}
回答by veritas
the approach you took is good. Just Implementation may need to be better. For instance ReturningValues should be well defined and Its better if you can make ReturningValues as immutable.
你采取的方法很好。只是实施可能需要更好。例如, ReturningValues 应该定义良好,如果您可以将 ReturningValues 设为immutable则更好。
// this approach is better
public static ReturningValues myMethod() {
ReturningValues rv = new ReturningValues("value", 12);
return rv;
}
public final class ReturningValues {
private final String value;
private final int index;
public ReturningValues(String value, int index) {
this.value = value;
this.index = index;
}
}
Or if you have lots of key value pairs you can use HashMap then
或者,如果您有很多键值对,则可以使用 HashMap
public static Map<String,Object> myMethod() {
Map<String,Object> map = new HashMap<String,Object>();
map.put(VALUE, "value");
map.put(INDEX, 12);
return Collections.unmodifiableMap(map); // try to use this
}
回答by Mukesh Kumar Singh
@ruchira ur solution it self is best.But i think if it is only about integer and a string we can do it in much easy and simple way..
@ruchira 你的解决方案它自己是最好的。但我认为如果它只是关于整数和一个字符串,我们可以用非常简单的方式来完成。
class B {
public String myfun() {
int a=2; //Integer .. you could use scanner or pass parameters ..i have simply assigned
String b="hi"; //String
return Integer.toString(a)+","+b; //returnig string and int with "," in middle
}
}
class A {
public static void main(String args[]){
B obj=new B(); // obj of class B with myfun() method
String returned[]=obj.myfun().split(",");
//splitting integer and string values with "," and storing them in array
int b1=Integer.parseInt(returned[0]); //converting first value in array to integer.
System.out.println(returned[0]); //printing integer
System.out.println(returned[1]); //printing String
}
}
i hope it was useful.. :)
我希望它有用.. :)
回答by Wendel
I create various return types using enum. It doesn't defined automatically. That implementation look like factory pattern.
我使用枚举创建了各种返回类型。它不会自动定义。该实现看起来像工厂模式。
public enum SmartReturn {
IntegerType, DoubleType;
@SuppressWarnings("unchecked")
public <T> T comeback(String value) {
switch (this) {
case IntegerType:
return (T) Integer.valueOf(value);
case DoubleType:
return (T) Double.valueOf(value);
default:
return null;
}
}
}
Unit Test:
单元测试:
public class MultipleReturnTypeTest {
@Test
public void returnIntegerOrString() {
Assert.assertTrue(SmartReturn.IntegerType.comeback("1") instanceof Integer);
Assert.assertTrue(SmartReturn.DoubleType.comeback("1") instanceof Double);
}
}
回答by Jay Wright
Method overloading can come in handy here Like:
方法重载在这里可以派上用场,例如:
<code>
public class myClass
{
int add(int a, int b)
{
return (a + b);
}
String add(String a, String b)
{
return (c + d);
}
public static void main(String args[])
{
myClass ob1 = new myClass);
ob1.add(2, 3);
//will return 5
ob1.add("Hello, ", "World!");
//will return Hello, World!
}
}
回答by ndm13
The class you're looking for already exists. Map.Entry
:
您要查找的课程已经存在。 Map.Entry
:
public static Entry<Integer,String> myMethod(){
return new SimpleEntry<>(12, "value");
}
And later:
然后:
Entry<Integer,String> valueAndIndex = myMethod();
int index = valueAndIndex.getKey();
String value = valueAndIndex.getValue();
It's just a simple two-field data structure that stores a key and value. If you need to do any special processing, store more than two fields, or have any other fringe case, you should make your own class, but otherwise, Map.Entry
is one of the more underutilized Java classes and is perfect for situations like these.
它只是一个简单的两字段数据结构,用于存储键和值。如果您需要进行任何特殊处理、存储两个以上的字段或有任何其他边缘情况,您应该创建自己的类,否则,它Map.Entry
是未充分利用的 Java 类之一,非常适合此类情况。
回答by Dante
I know this is late but I thought it'd be helpful to someone who'll come searching for an answer to this. You can use a Bundle
to return multiple datatype values without creating another method. I tried it and worked perfectly.
我知道这已经晚了,但我认为这对来寻找答案的人会有所帮助。您可以使用 aBundle
返回多个数据类型值,而无需创建其他方法。我试过了,效果很好。
In Your MainActivity where you call the method:
在您调用方法的 MainActivity 中:
Bundle myBundle = method();
String myString = myBundle.getString("myS");
String myInt = myBundle.getInt("myI");
Method:
方法:
public Bundle method() {
mBundle = new Bundle();
String typicalString = "This is String";
Int typicalInt = 1;
mBundle.putString("myS", typicalString);
mBundle.putInt("myI", typicalInt);
return mBundle;
}
P.S: I'm not sure if it's OK to implement a Bundle like this, but for me, it worked out perfectly.
PS:我不确定实现这样的 Bundle 是否可以,但对我来说,它完美无缺。