Interfaces - Exercises
Iterators
wouldn't it be nice to iterate through any Collection or array easily like this
class MainClass {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList();
int[] ints = {100, 200, 300};
for (int i = 0; i <= 50 ; i+=10)
list.add(i);
for (int elem : list)
System.out.print(elem + "\t");
System.out.println();
for (int elem : ints)
System.out.print(elem + "\t");
}
}we can use the power of iterators
example
our IntList now implements Iterable
As we can see we call the iterator function (another name would implement (override) the Iterator) and return an object of type Iterator
iterator has 2 functions
hasNext()return booleannext()returns the next item
now we can use a for-each
🤔 How would write an iterator for a linkedList? Its not so difficult
Comparator
change in Point
implemented Comparable, now we can sort
overrided
compareTofunction
Test Question


Note: the answer can be much simpler but I trying to teach a few ideas
or this
we could also use
if we implement Comparator
or even doing this
Exercise: Student and Grade
and get something like this
we are sorting by the grade average
We will need to make 2 classes
Grade
String subject
double grade
Student
static int rollno
String name
int age
List<Grade> grades
solution
we don't have to implement Iterator since we are using Java Arraylist
GUIs - Not on the test!
what else can we use interfaces for?
for GUIs
ActionListener is an interface we implement add to the addActionListener() on a button
Last updated
Was this helpful?