2

In Java, sometimes I need to return a struct variable like Point(x,y). However, I only use this result in 1 place of the code and 1 time. So it seems excessive to declare a class called Point. Is there a way to return some kind of anonymous object with x number of parameters?

delita
  • 1,571
  • 1
  • 19
  • 25

2 Answers2

1

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. In your example, x and y are of type int or double I guess, but still.

If you want some 'anonymous' class, it still needs a class signature. You might want to make Point as an innerclass, something like this:

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.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
0

You can return Array or ArrayList.

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

    arr = new int[len];

    // Business logic
    // ...

    return arr;
}
Azodious
  • 13,752
  • 1
  • 36
  • 71