Reading notes : java.util.Collection

statement !!!

all the contents below excerpt from "Introduction to Java Programming, Comprehensive Version 10th edition"

The Java Collections Framework

Collection  Interface  method

Each collection is Iterable . You can obtain its Iterator object to traverse all the elements in the collection.

Iterator is a classic design pattern for walking through a data structure without having to expose the details of how data is stored in the data structure.

import java.util.*;
Collection<String> collection = new ArrayList<>();
ArrayList<String> collection1 = new ArrayList<>();

Iterator<String> iterator = collection.iterator();
while (iterator.hasNext()) {
    System.out.print(iterator.next().toUpperCase() + " ");
}

//foreach loop
for (String element: collection)
    System.out.print(element.toUpperCase() + " ");

Note: All the concrete classes in the Java Collections Framework implement the java.lang.Cloneable and java.io.Serializable interfaces except that java.util.PriorityQueue does not implement the Cloneable interface. Thus,all instances of Cloneable except priority queues can be cloned and all instances of Cloneable can be serialized.

List

Interface method

ArrayList & LinkedList

difference 1 : store elements in a different way

ArrayList is a resizable-array implementation of the List interface, stores elements in an array.

The array is dynamically created. If the capacity of the array is exceeded, a larger new array is created and all the elements from
the current array are copied to the new array.

LinkedList is a linked list implementation of the List interface, stores elements in a linked list.

difference 2 : different operations

LinkedList class provides the methods for retrieving, inserting, and removing elements from both ends of the list.

efficiency:
     ArrayList is efficient for retrieving elements and LinkedList is efficient for inserting and removing elements at the beginning of
the list. Both have the same performance for inserting and removing elements in the middle or at the end of the list.

    If you need to support random access through an index without inserting or removing elements at the beginning
of the list
, ArrayList offers the most efficient collection. If, however, your application requires the insertion or deletion of elements at the beginning of the list, you should choose LinkedList. 

ArrayList constructors

LinkedList

import java.util.*;
List<Integer> arrayList = new ArrayList<>();
LinkedList<Object> linkedList = new LinkedList<>(arrayList);

ListIterator<Object> listIterator = linkedList.listIterator();
while (listIterator.hasNext()) {
    System.out.print(listIterator.next() + " ");
}

listIterator = linkedList.listIterator(linkedList.size());
while (listIterator.hasPrevious()) {
    System.out.print(listIterator.previous() + " ");
}

//Java provides the static asList method for creating a list from a variable-length list of arguments.

List<String> list1 = Arrays.asList("red", "green", "blue");
List<Integer> list2 = Arrays.asList(10, 20, 30, 40, 50);

Caution:

   The get(i) method is available for a linked list, but it is a time-consuming operation. Do not use it to traverse all the elements in a list as shown in (a). Instead you should use an iterator as shown in (b).

The Comparator Interface

     Comparator can be used to compare the objects of a class that doesn’t implement Comparable .The Comparable interface defines the compareTo method, which is used to compare two elements of the same class that implement the Comparable interface.

How to do:

     define a class that implements the java.util.Comparator<T> interface and overrides its compare method.

                public int compare(T element1, T element2)
     Returns a negative value if element1 is less than element2 , a positive value if element1 is greater than element2 , and zero if they are equal.

import java.util.Comparator;

//  the GeometricObject Interface defines some abstract methods for its concrete class such as rectangle, circle

public class GeometricObjectComparator implements Comparator<GeometricObject>, java.io.Serializable {
//override compare method from java.util.Comparator<T> interface
public int compare(GeometricObject o1, GeometricObject o2) {
    double area1 = o1.getArea();
    double area2 = o2.getArea();
    if (area1 < area2)
        return -1;
    else if (area1 == area2)
        return 0;
    else
        return 1;
    }
}

public class TestComparator {
    public static void main(String[] args) {
        GeometricObject g1 = new Rectangle(5, 5);
        GeometricObject g2 = new Circle(5);
        GeometricObject g = max(g1, g2, new GeometricObjectComparator());
        System.out.println("The area of the larger object is " +
        g.getArea());
    }
    public static GeometricObject max(GeometricObject g1, GeometricObject g2, Comparator<GeometricObject> c) {
        if (c.compare(g1, g2) > 0)
            return g1;
        else
            return g2;
    }
}

Note:

     Comparable is used to compare the objects of the class that implement Comparable. Comparator can be used to compare the objects of a class that doesn’t implement Comparable .
     Comparing elements using the Comparable interface is referred to as comparing using natural order, and comparing elements using the Comparator interface is referred to as comparing using comparator.

 

Static Methods for Lists and Collections

The Collections class contains static methods to perform common operations in a collection and a list.

 

Vector and Stack Classes

     Vector is a subclass of AbstractList, same as ArrayList , except that it contains synchronized methods for accessing and modifying the vector. Synchronized methods can prevent data corruption when a vector is accessed and modified by two or more threads concurrently. For the many applications that do not require synchronization, using ArrayList is more efficient than using Vector .

   

     Stack is a subclass of Vector

Queues

      A queue is a first-in, first-out data structure. Elements are appended to the end of the queue and are removed from the beginning of the queue. In a priority queue, elements are assigned priorities. When accessing elements, the element with the highest priority is removed first.

Priority Queues

       The PriorityQueue class implements a priority queue, as shown in figure below. By default, the priority queue orders its elements according to their natural ordering using Comparable . The element with the least value is assigned the highest priority and thus is removed from the queue first. If there are several elements with the same highest priority, the tie is broken arbitrarily. You can also specify an ordering using Comparator in the constructor PriorityQueue(initialCapacity, comparator) .

 

Deque

      The LinkedList class implements the Deque interface, which extends the Queue interface. Deque supports element insertion and removal at both ends. The name deque is short for “double-ended queue” and is usually pronounced “deck.”

Sets and Maps

A set is an efficient data structure for storing and processing nonduplicate elements.
A map is like a dictionary that provides a quick lookup to retrieve a value using a key.

Sets

    You can create a set using one of its three concrete classes: HashSet , LinkedHashSet , or TreeSet .

HashSet

      An empty hash set can be created by its no-arg constructor or to create a hash set from an existing collection. By default,
the initial capacity is 16 and the load factor is 0.75 .
The load factor is a value between 0.0 and 1.0 .

      The load factor measures how full the set is allowed to be before its capacity is increased. When the number of elements exceeds the product of the capacity and load factor, the capacity is automatically doubled. Generally, the default load factor 0.75 is a good trade-off between time and space costs.

the hashCode method

     Objects added to a hash set need to implement the hashCode method in a manner that properly disperses the hash code. Implementing the hashCode method to avoid too many such cases where two unequal objects may have the same hash code is necessary.

     Thus most of the classes in the Java API implement the hashCode method. For example, the hashCode in the Integer class returns its int value. The hashCode in the Character class returns the Unicode of the character. The hashCode in the String class returns s 0 * 31 (n - 1) + s 1 * 31 (n - 2) + c + s n - 1 , where s i is s.charAt(i) .

LinkedHashSet

      LinkedHashSet extends HashSet with a linked-list implementation that supports an ordering of the elements in the set. The elements in a HashSet are not ordered, but the elements in a LinkedHashSet can be retrieved in the order in which they were inserted into the set.

     Tip
     If you don’t need to maintain the order in which the elements are inserted, use HashSet ,which is more efficient than LinkedHashSet.

TreeSet

    If you create a TreeSet using its no-arg constructor, the compareTo method is used to compare the elements in the set, assuming that the class of the elements implements the Comparable interface. To use a comparator, you have to use the constructor TreeSet(Comparator
comparator)
to create a sorted set that uses the compare method in the comparator to order
the elements in the set.

     New Methods in SortedSet :

     SortedSet is a subinterface of Set , which guarantees that the elements in the set are sorted.

     first() ,  last() : returning the first and last elements in the set

     headSet(toElement) , tailSet(fromElement) : returning a portion of the set whose elements are less than toElement and greater than or equal to fromElement , respectively.

     New Methods in NavigableSet:
     NavigableSet extends SortedSet to provide navigation methods.

     lower(e) ,floor(e) , ceiling(e) , higher(e) : returning elements respectively less than, less than or equal, greater than or equal, and greater than a given element and return null if there is no such element.

     pollFirst() , pollLast() : removing and returning the first and last element in the tree set, respectively.

import java.util.*;
Set<String> set = new HashSet<>();
TreeSet<String> treeSet = new TreeSet<>(set);

   Tip
   If you don’t need to maintain a sorted set when updating a set, you should use a hashset, because it takes less time to insert and remove elements in a hash set. When you need a sorted set, you can create a tree set from the hash set.

 

Maps

   A map is a container object that stores a collection of key/value pairs.  In Map , the keys can be any objects. A map cannot contain duplicate keys. Each key maps to one value.

A map can be created using its three concrete classes: HashMap ,LinkedHashMap , TreeMap .

The entries are instances of the Map.Entry<K, V> interface, where Entry is an inner interface for the Map interface.

The Java Collections Framework provides three concrete map classes.

LinkedHashMap

      LinkedHashMap extends HashMap with a linked-list implementation that supports an ordering of the entries in the map. The entries in a HashMap are not ordered, but the entries in a LinkedHashMap can be retrieved either in the order in which they were inserted into the map (known as the insertion order) or in the order in which they were last accessed, from least recently to most recently accessed (access order). The no-arg constructor constructs a LinkedHashMap with the insertion order. To construct a LinkedHashMap with the access order, use LinkedHashMap(initialCapacity, loadFactor, true) .

TreeMap

     The TreeMap class is efficient for traversing the keys in a sorted order. The keys can be sorted using the Comparable interface or the Comparator interface. If you create a TreeMap using its no-arg constructor, the compareTo method in the Comparable interface is used to compare the keys in the map, assuming that the class for the keys implements the
Comparable interface. To use a comparator, you have to use the TreeMap(Comparator comparator) constructor to create a sorted map that uses the compare method in the comparator to order the entries in the map based on the keys.

New Methods in SortedSet :
      SortedMap is a subinterface of Map , which guarantees that the entries in the map are sorted. 

      firstKey() ,  lastKey() : returns the first and last keys in the map

      headMap(toKey) , tailMap(fromKey) : returns a portion of the map whose keys are less than toKey and greater than or equal to fromKey , respectively.

New Methods in NavigableMap :
    NavigableMap extends SortedMap to provide the navigation methods .  

    lowerKey(key) ,floorKey(key) , ceilingKey(key) ,  higherKey(key) return keys respectively less than, less than or equal, greater than or equal, and greater than a given key and return null if there is no such key.

    pollFirstEntry() , pollLastEntry()  remove and return the first and last entry in the tree map, respectively.

Note
     Prior to Java 2, java.util.Hashtable was used for mapping keys with values. Hashtable was redesigned to fit into the Java Collections Framework with all its methods retained for compatibility. Hashtable implements the Map interface and is used in the
same way as HashMap , except that the update methods in Hashtable are synchronized.

Tip
    If you don’t need to maintain an order in a map when updating it, use a HashMap .When you need to maintain the insertion order or access order in the map, use a LinkedHashMap . When you need the map to be sorted on keys, use a TreeMap .

 

Singleton and Unmodifiable Collections and Maps

     The Collections class contains the static methods for lists and collections. It also contains the methods for creating immutable singleton sets, lists, and maps, and for creating read-only sets, lists, and maps. The Collections class defines three constants— EMPTY_SET , EMPTY_LIST , EMPTY_MAP —for an empty set, an empty list, and an empty map.

    The class also provides the singleton(Object o) method for creating an immutable set containing only a single item

    The Collections class also provides six static methods for returning read-only views for collections: unmodifiableCollection(Collection c) , unmodifiableList(List list) and the rest.  This type of view is like a reference to the actual collection.

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值