Diploma in Nursing Admission Test Question Solution 2023.pdf
Oop lecture8
1. Lecture 8
More on collections
Object Oriented Programming
Eastern University, Dhaka
Md. Raihan Kibria
2. LinkedList
LinkedList is just like ArrayList; however, it
was designed to make add/remove faster
and efficient
Has these methods:
addFirst
AddLast
removeFirst
removeLast
4. Sets
Examples are HashSet, TreeSet
Difference between Set and List
A list can have duplicate objects
Set cannot have duplicate objects
See example in the next slide
5. Output
size of set: 4
0
1
2
3
size of list: 5
0
1
2
3
3
We can see set did not add duplicate element
6. public class SetDemo {
public static void main(String[] args) {
Set<Integer>set = new HashSet<Integer>();
List<Integer>list = new ArrayList<Integer>();
for (int i=0; i<4; i++){
set.add(new Integer(i));
list.add(new Integer(i));
}
set.add(3);
list.add(3);
System.out.println("size of set: " + set.size());
for (int i=0; i<set.size(); i++)
System.out.println(set.toArray()[i]);
System.out.println("size of list: " + list.size());
for (int i=0; i<list.size(); i++)
System.out.println(list.get(i));
}
}
Output in the following slide
7. Map interface
Object to a map are key,value pairs
For example,
<dhaka, 02>
<chittagong, 031>
<sylhet, 032>
Two most common map implementations
are HashMap and TreeMap
8. HashMap example
public class MapDemo {
public static void main(String[] args) {
Map<String, Integer>map = new HashMap<String, Integer>();
map.put("Dhaka", 2);
map.put("Chittagong", 31);
map.put("Sylhet", 32);
System.out.println(map.get("Chittagong"));
System.out.println(map.get("Comilla"));
}
}
Output is:
31
null