Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Method that can return a collection OR list of any type

Options
  • 07-01-2014 5:40pm
    #1
    Registered Users Posts: 5,558 ✭✭✭


    Hi, ive a requirement to return the following in one method.

    This should be implemented so that any list/collection can be filtered.

    So the method signature needs something exotic i guess...

    I know a small bit of generics but overall am kinda stuck on this.

    public List<? extends Collection> doStuff(List listToBeHandled<? extends Collection>, double percentage, int offset)

    Is there any handy way to do this? My above approach aint working. Thanks if you can help


Comments

  • Registered Users Posts: 1,109 ✭✭✭Skrynesaver


    So your method has to handle a list of any type of object, I wonder is there a class that every other class can be cast into which you could then cast your list from ...


  • Registered Users Posts: 5,558 ✭✭✭veryangryman


    So your method has to handle a list of any type of object, I wonder is there a class that every other class can be cast into which you could then cast your list from ...

    I wish your Sarcasm was helpful. As the question says, i need it to handle the 2 grouping mechanisms Lists or Collections, not just lists. The object type doesnt matter for the purpose of the question.


  • Closed Accounts Posts: 8,015 ✭✭✭CreepingDeath


    A list extends the collection class.
    Why can't you do this ?
        public Collection<?> doStuff(Collection<?> col, double percentage, int offset)
        {
            // do stuff
            
            return(null);
        }
    


  • Registered Users Posts: 47 cregganna


    A list extends the collection class.
    Why can't you do this ?
        public Collection<?> doStuff(Collection<?> col, double percentage, int offset)
        {
            // do stuff
            
            return(null);
        }
    

    Better still parametrise the generic either through a type on the implemented interface or even directly on the method signature:
        public <T> Collection<T> doStuff(Collection<T> col, double percentage, int offset);
    

    That way you can garuntee that the return collection type matches that passed in.


  • Registered Users Posts: 5,558 ✭✭✭veryangryman


    Bingo.

    Thanks for the help folks! :D


  • Advertisement
Advertisement