简体   繁体   English

返回x参数匿名对象

[英]Return x param anonymous object

In Java, sometimes I need to return a struct variable like Point(x,y). 在Java中,有时我需要返回一个Point(x,y)之类的结构变量。 However, I only use this result in 1 place of the code and 1 time. 但是,我只在代码的1个位置和1次使用此结果。 So it seems excessive to declare a class called Point. 因此,声明一个名为Point的类似乎过多。 Is there a way to return some kind of anonymous object with x number of parameters? 有没有办法返回带有x个参数的某种匿名对象?

You can return an ArrayList , but then the problem is, an ArrayList is bound to one specific type, so if those parameters have different types, you have to typecast them. 您可以返回ArrayList ,但是问题是, ArrayList绑定到一种特定的类型,因此,如果这些参数具有不同的类型,则必须进行类型转换。 In your example, x and y are of type int or double I guess, but still. 在您的示例中,我猜xy的类型为intdouble ,但仍然如此。

If you want some 'anonymous' class, it still needs a class signature. 如果您想要一些“匿名”类,它仍然需要一个类签名。 You might want to make Point as an innerclass, something like this: 您可能希望将Point设为内部类,如下所示:

public class SomeClass {
    class Point {
        private int x;
        private int y;
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    private Point p;
}

Why nested classes? 为什么要嵌套类? The Java™ Tutorials Point out why. 在Java™教程 Point原因。

You can return Array or ArrayList . 您可以返回ArrayArrayList

int[] GetPoint( ... )
{
    int[] arr = null;
    // ...
    // Find length (say len)

    arr = new int[len];

    // Business logic
    // ...

    return arr;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM