OOP Ch06 Generics and Collections
OOP Ch06 Generics and Collections
https://www.javatpoint.com/collections-in-java
3 types of group:
List can contain duplicate elements
Set can contain distinct elements only
Map can contain pairs <key, value>. Key of element is data for fast searching
keySet() Use
values() iterator
List
Lists
• A List keeps it elements in the order in which they were added.
• Each element of a List has an index, starting from 0.
• Common methods:
• void add(int index, Object x)
• Object get(int index)
• int indexOf(Object x)
• Object remove(int index)
• Classes Implementing the interface List
• AbstractList
• ArrayList
• Vector (like ArrayList but it is synchronized)
• LinkedList: linked lists can be used as a stack, queue, or double-ended queue
(deque)
List Implementations
• ArrayList Collection
• low cost random access
• high cost insert and
delete
List
• array that resizes if need
be
• LinkedList ArrayList LinkedList
• sequential access
• low cost insert and
delete
• high cost random access
ArrayList
• ArrayList is a class that
implements the List interface.
• The advantage of ArrayList over
the general Array is that ArrayList
is dynamic and the size of
ArrayList can grow or shrink.
• ArrayList stores the elements in
the insertion order.
• ArrayList can have duplicate
elements. ArrayList is non
synchronized.
Methods (1)
Methods Description
void add(int index, Inserts the specified element at the specified position in this
Object element) list.
boolean add(Object o) Appends the specified element to the end of this list.
boolean Appends all of the elements in the specified collection to the
addAll(Collection c) end of this list, in the order that they are returned by the
specified collection's Iterator
void clear() Removes all of the elements from this list.
boolean returns true if this list contains the specified element.
contains(Object o)
Object get(int index) returns the element at the specified position in this list.
Methods (2)
Methods Description
protected void removes from this list all of the elements whose index is
removeRange(int between fromIndex(inclusive) and toIndex(exclusive).
fromIndex, int toIndex)
Object set(int index, Object replaces the element at the specified position in this list with
element) the specified element.
int size() returns the number of elements in this list.
int indexOf(Object o) returns the index of the first (last) occurrence of the
int lastIndexOf(Object o) specified element in this list, or -1 if this list does not contain
the element.
Object remove(int index) removes the element at the specified position in this
list.
boolean remove(Object o) removes the first occurrence of the specified element from this list,
if it is present.
public class ArrayListDemo {
public static void main(String args[]){
ArrayList al = new ArrayList();
Example
System.out.println(“The size at beginning: " +
al.size());
//add elements
al.add("C"); al.add("A");
al.add("E"); al.add("B");
al.add("D"); al.add("F");
al.add(1, "A2");
System.out.println(“The size after: " + al.size());
System.out.println(“Content: " + al);
al.remove("F"); al.remove(2);
System.out.println(“The Size after to remove:"+ al.size());
System.out.println(“Content: " + al);
}
} The size at beginning: 0
The size after: 7
Content: [C, A2, A, E, B, D, F]
The Size after to remove: 5
Content: [C, A2, E, B, D]
Vector
• Vector implements a dynamic array. It is similar to ArrayList, but with two
differences
• Vector is synchronized.
• Vector contains many legacy methods that are not part of the collections
framework.
• Constructors:
• Vector( ):This constructor creates a default vector, which has an initial
capacity of 10.
• Vector(int size):This constructor accepts an argument that equals to the
required size
• Vector(int size, int incr): This constructor creates a vector whose initial
capacity is specified by size and whose increment is specified by incr.
• Vector(Collection c): This constructor creates a vector that contains the
elements of collection c.
Methods (1)
void add(int index, Object element)
Inserts the specified element at the specified position in this Vector.
boolean add(Object o):Appends the specified element to the end of this Vector.
boolean addAll(Collection c)
Appends all of the elements in the specified Collection to the end of this Vector
void clear(): Removes all of the elements from this vector.
boolean contains(Object elem): Tests if the specified object is a component in this vector.
boolean containsAll(Collection c)
Returns true if this vector contains all of the elements in the specified Collection.
Object elementAt(int index): Returns the component at the specified index.
boolean equals(Object o): Compares the specified Object with this vector for equality.
Methods (2)
Object firstElement(): Returns the first component (the item at index 0) of this vector.
Object get(int index): Returns the element at the specified position in this vector.
int indexOf(Object elem), int indexOf(Object elem, int index) : Searches for the first occurence
of the given argument (beginning the search at index, ), testing for equality using the equals
method.
void insertElementAt(Object obj, int index)
Inserts the specified object as a component in this vector at the specified index.
boolean isEmpty(): Tests if this vector has no components.
Object lastElement(): Returns the last component of the vector.
Object remove(int index), boolean remove(Object o): Removes the element at the specified
position in this vector. Removes the first occurrence of the specified element in this vector,
void removeAllElements()
Removes all components from this vector and sets its size to zero.
Methods (3)
Object set(int index, Object element)
Replaces the element at the specified position in this vector with the specified element.
int size(): Returns the number of components in this vector.
List subList(int fromIndex, int toIndex)
Returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive.
Object[] toArray()
Returns an array containing all of the elements in this vector in the correct order.
String toString()
Returns a string representation of this vector, containing the String representation of each
element.
void trimToSize()
Trims the capacity of this vector to be the vector's current size.
LinkedList overview
• Stores each element in a private static class Entry {
Object element;
node Entry next;
• Each node stores a link to the Entry previous;
next and previous nodes Entry(Object element, Entry
next, Entry previous) {
• Insertion and removal are this.element = element;
inexpensive this.next = next;
this.previous = previous;
• just update the links in the }
surrounding nodes }
• Linear traversal is inexpensive private Entry header = new
Entry(null, null, null);
• Random access is expensive public LinkedList() {
header.next = header.previous
• Start from beginning or end = header;
and traverse each node while }
counting
LinkedList methods
• The list is sequential, so access it that way
• ListIterator listIterator()
• ListIterator knows about position
• use add() from ListIterator to add at a position
• use remove() from ListIterator to remove at a position
• LinkedList knows a few things too
• void addFirst(Object o), void addLast(Object o)
• Object getFirst(), Object getLast()
• Object removeFirst(), Object removeLast()
• Example: Polynomial
• 0.45 - 1.89 x2 + 3.4 x5 + 9 x16
Generic in java
• The Java Generics programming is introduced in Java SE 5 to deal with
type-safe objects.
• Generics, forces the java programmer to store specific type of objects.
• There are mainly 3 advantages of generics:
• Type-safety : We can hold only a single type of objects in generics. It
doesn’t allow to store other objects.
• Type casting is not required: There is no need to typecast the object.
we need to type cast.
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
• we don't need to typecast the object.
List<String> list =new ArrayList<String>();
list.add("hello");
String s = list.get(0);
Generic in java…
• Compile-Time Checking: It is checked at compile time so problem will not occur at
runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile Time Error
Good Type Variable Names
Type Variable Name Meaning
E Element type in a collection
K Key type in a map
V Value type in a map
T General type
S, U Additional general types
Set
Sets
• Lists are based on an void addTwice(Set set) {
ordering of their members.
set.clear();
Sets have no concept of
order. Point p1 = new Point(10, 20);
Point p2 = new Point(10, 20);
• A Set is just a cluster of
references to objects. set.add(p1);
set.add(p2);
• Sets may not contain
duplicate elements. System.out.println(set.size());
}
• Sets use the equals()
method, not the ==
operator, to check for will print out 1, not 2.
duplication of elements.
Sets…
• Set extends Collection but does not add any additional methods.
• The two most commonly used implementing classes are:
• TreeSet
• Guarantees that the sorted set will be in ascending element order.
• log(n) time cost for the basic operations (add, remove and contains).
• HashSet
• Constant time performance for the basic operations (add, remove, contains and
size).
• Ordered Tree – Introduced in the suject Discrete Mathematics
• Set: Group of different elements
• TreeSet: Set + ordered tree, each element is calles as node
• Iterator: An operation in which references of all node are grouped to make a linked list.
Iterator is a way to access every node of a tree.
• Linked list: a group of elements, each element contains a reference to the next
TreeSet = Set + Tree The result may be:
(O(1)).
5 Smith
“Smith” f 5