One of the things that has me stumbling for some time in interviews is the fact that their methods have List interface as a parameter and a return type. Comsider something like this:
public List<Interval> merge(List<Interval> intervals) {
if(intervals.length()==0) return null; //does not work
}
Above, Eclipse complains 'The method length() is undefined for the type List'. Similarly I can't iterate in a for loop using intervals.length()
I have searched this online and on other posts and I'm aware that in Java an Interface is a framework and we cannot instantiate it. But the questions says that a list of Intervals is provided in the method(data input) and I need to iterate over the List and do some merge work. How do I do that since I can't seem to even access the List. I know that in Java we can initialize a concrete class of an interface like:
List<Integer> ll = new ArrayList<>();
But doing this in the above method would lose all the existing data I get in the parameter. Another method I saw in another SO post was something like this:
if(intervals instanceOf ArrayList){
//Do some work
}
But obviously I cannot check for each instance that the interface can implement, can I? I mean it doesn't seem practical.
Can someone please explain how to iterate over data in a method accepts a interface/List?