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?
            Asked
            
        
        
            Active
            
        
            Viewed 121 times
        
    2
            
            
        - 
                    5return int[] with two elements. – Usman Saleem Jan 22 '13 at 05:55
- 
                    @UsmanSaleem that removes all semantics of what each element is, and it need not be both ints. – Karthik T Jan 22 '13 at 05:56
- 
                    I believe OP is looking for something like perl's `my ($one, $two) = get_two();` – Karthik T Jan 22 '13 at 05:57
- 
                    @KarthikT I responded based on 'Point(x,y)' as mentioned by poster. – Usman Saleem Jan 22 '13 at 05:57
- 
                    1You can try writing something like a generic tuple class and using those to return your values, this could then be reused in other parts of your code - see [Using Tuples in Java](http://stackoverflow.com/q/2670982) for more info – Karthik T Jan 22 '13 at 06:01
- 
                    or an `Object[]` with two elements if not both ints – Jakob Weisblat Jan 22 '13 at 06:02
- 
                    1possible duplicate: http://stackoverflow.com/questions/11968265/return-more-than-one-variable-from-java-method?lq=1 – Jakob Weisblat Jan 22 '13 at 06:03
- 
                    1+1 for declaring a class called `Point`, -1 for _thinking_ that's excessive. Java deliberately doesn't provide tuple classes because it really isn't that difficult to write your own custom one with useful names for the parameters. – Louis Wasserman Jan 22 '13 at 06:08
2 Answers
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
