-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathD5-1.txt
60 lines (51 loc) · 1.58 KB
/
D5-1.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.util.List;
import java.util.Iterator;
import java.util.LinkedList;
class Course {
String courseName;
public Course(String courseName) {
this.courseName = courseName;
}
@Override
public String toString() {
return courseName;
}
}
class ListInterface {
public static void main(String[] args) {
List<Course> courseList = new LinkedList<>();
courseList.add(new Course("Java"));
courseList.add(new Course("Hibernate"));
courseList.add(new Course("AngularJS"));
// Accessing the list of courses Using Iterator
Iterator<Course> courseIterator = courseList.iterator();
System.out.println("Using Iterator to access the list of courses");
while (courseIterator.hasNext()) {
Course c = courseIterator.next();
System.out.println(c); // toString() method has been overridden in the Course class
}
// Accessing the list of courses Using for loop
System.out.println("Using for loop to access the list of courses");
for (int index = 0; index < courseList.size(); index++) {
System.out.println(courseList.get(index));
}
// Accessing the list of courses Using enhanced for loop (for-each)
System.out.println("Using enhanced for loop to access the list of courses");
for (Course c : courseList) { // Can be read as: for each Course c in courseList
System.out.println(c);
}
}
}
Output:
Using Iterator to access the list of courses
Java
Hibernate
AngularJS
Using for loop to access the list of courses
Java
Hibernate
AngularJS
Using enhanced for loop to access the list of courses
Java
Hibernate
AngularJS