Iterable vs Iterator as return behavior (Best Practice?)

I just want to know your opinion on how to change the entire output function of Collections to type Iterable.

It seems to me that this is the most common code in Java these days, and everyone always returns List / Set / Map in 99% of cases, but should not be a standard return of something like

    public final Iterable<String> myMethod() {
            return new Iterable<String>() {
                  @Override
                  public Iterator<String> iterator() {return myVar.getColl();}
            };
    }

Is it really bad? You know all the DAO classes, and this stuff will look like

    Iterable<String> getName(){}
    Iterable<Integer> getNums(){}
    Iterable<String> getStuff(){}

instead

    List<String> getName(){}
    List<Integer> getNums(){}
    Set<String> getStuff(){}

In the end, 99% of the time you'll use it in a for ... loop

What do you think?

+3
source share
3 answers

It will be a very bad plan.

, 90% for. , 40-50%. : size, contains get(int).

, - . Set , . List, .

, HashSet ArrayList, Set List, Collection Iterable, .

+3

, - , . , .

List/etc Iterable/Iterator - . , , Iterable . , , . : .

, , . , , . .

: , , , . , , , , , .

+2

Well, what you encoded is partially correct:

you need to test some methods of elements such as:

  • size
  • contains()
  • get(index)
  • exists()

So, you have to rethink your new architecture or redefine it with this method in order to do what you need each time.

0
source

All Articles