1

For some reason, this doesn't work

    import java.util.*;

 public class SetExample
    {
public static void main(String[] args)
{

    System.out.println(set().next().length());

}

public static Iterator set()
{
    List<String> arr = new ArrayList<>(Arrays.asList("one", "fableeblee", "cacao", "pablo", "thelma", "hepatitis"));
    Iterator<String> itr = arr.iterator();
    System.out.println(itr.next().length());
    return itr;
}   
}   

The one line in main gives me a "cannot find symbol error", but a method similar to it in the set() method works. Why is this? It works perfectly fine in main when I remove the .length(), but with it, it doesn't work.

squidword
  • 437
  • 3
  • 11

2 Answers2

3

Your method set has a return type of Iterator, not Iterator<String>, so when you receive an Iterator from the method's return, the machine cannot know what is inside of it, and thus length cannot be used on a general Object.

To fix this, add Iterator<String> as the return type instead of Iterator.

To clarify, this is essentially encapsulation at work. Methods outside of set do not know what goes on inside of it, only that it returns an Iterator.

Zircon
  • 4,677
  • 15
  • 32
2

You are returning a raw iterator, and the length() method is undefined for its elements. Change your set() method to return Iterator<String>.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Elsinor
  • 190
  • 8