Monday 5 January 2015

SCJP notes: collections and generics

Miscellaneous

  • Most of collections classes are not final, so they could be subclassed

Maps:
  • Map doesn't implement Collection
  • Map doesn't have the contains() as all collections, but it has containsKey() and containsValue()  methods
  • Map implementations: TreeMap, Hashtable, HashMap. LinkedHashMap
  • LinkedHashMap extends HashMap is ordered Map
  • Hashtable is HashMap with synchronized methods
  • Hashtable, HashMap  not sorted and not ordered
  • HashMap allows null as key, all other implementation will throw nullpointer, when you try to add it
  • When you add duplicate in map, it replace previous value
  • For Map sometimes it is critical to override equals and hashcode to get your value back from Map
  • If you will try to add to the TreeMap something that is not Comparable, you will get at this time ClassCastException
  • Or you can supply to the TreeMap constructor the comparator, to avoid previously mentioned exception.
  • If you want to iterate throw Map, you need to call the entrySet() method, and then can call iterator from it. Map itself doesn't have the iterator
Sets:
  • Set implementations: TreeSet, HashSet, LinkedHashSet
  • Couldn't get element by index, need iterator or for-each construction
Navigating TreeMaps and TreeSets:
  • TreeMaps and TreeSets are sorted in natural ascending order 
  • TreeMap has methods like: higherKey(), lowerKey(), floorKey(), ceilingKey()
  • TreeSet has methods like: higher(), lower(), floor(), ceiling()
  • higherXXX() returns the element is smaller than the asked one
  • ceilingKeyXXX()  returns the element is smaller or equals that the asked one
  • TreeMap and TreeSet has descendingXXX() method
  • TreeSet hass pollFirst() and pollLast() methods that returnas and removes from the collection the first or last items
  • For TreeMap the same, but just pollFirstEntry() or pollLastEntry() 
Lists:
  • List implementations: ArrayList, LinkedList, Vector
  • LinkedList implemenst the Queue inteface
  • The add(<something to add>) method adds to the end of the list 
  • Or the add(int index, <something to add>) method  adds to the specified index position and moves all element with index higher or equals of specified index.
  • The set(int index, <something to add>) method replace existing value by index, could get IndexOutOfBoundsException if there is no such value by index that should be replaced
  • The sublist method returns the baked sublist with left borde inclusive and right border exclusive, you can also specify both borders with the same value, it will return empty list
Queues:
  • Queue implementations: LinkedList, PriorityQueue
  • PriorityQueue just sorted queue
  • Queue inteface and so on PriorityQueue has method offer() that is used to add something to the queue, and no methods as offerFirst() and offerLast() 
  • LinkedList has the offerFirst() and offerLast() methods
Backed collections
  • Everything that implements collection (everything except maps) has toArray() methods
  • The first of toArray() takes nothing and returns the array of Object
  • The second of toArray() takes the array of the type of the generics Collection, returns this array populated with the Collection items if the capacity of this array is enough, and new array of the same type if no.
  • This array is not backed with the Collection from which it was derived
  • If you will try to derive the list from the array of primitives you will get the list of arrays of these primitives.
  • Arrays.asList() return the generic list of the type of the passed array, backed together. Backed means that the list will be fixed size (you will get exception trying to add something), but if you change something in this collection the array will know about it, and the vice versa.
Sorting and searching throw collections and arrays
  • Collections (only for Lists) and Arrays classes has the sort() method that has two flavors: the first takes Comparable Collection; the second takes Collection and Comparator
  • Both Comparable and Comparator could be parameterized by generics
  • Collections (only for Lists) and Arrays classes has the binarySearch() method, this method searches throw sorted List or array and returns the index of the element if it was found
  • If the searched List or array wasn’t sorted the result of the search in unpredictable
  • If the searched List or array doesn't contains the searched element it will return the index where this element could be added with no braking sort - 1
  • Collections has the reverseOrder() method which takes Comparator and returns the reverse order Comparator
  • Collections has the reverseOrder() method which takes nothing and returns the reverse order Comparator for all Comparable objects, but if you try to sort or search with this Comparator something that is not Comparable you will get ClassCastException
  • During binary search, if one object equals another one will be taken not from equals() method, but from Comparator or compareTo(). So if Comparator or compareTo() contradict the equals() method you could find sometimes something unexpected 
  • Emty String is the first String after sorting
Generics
  • Generics doesn't exist in runtime
  • To the List<Object> you can add everything of Object's subclass 
  • You can always pass the generic Collection to the method that take non-generic ones, but you will get compiler warning for it
  • If you will try to add something to the Collection in such method that is not the type of what the Collection is generified, you won't get any exception until you will try to get something from this Collection there you can get ClassCastException. The same exception you will get trying to sort such List.
  • This wildcard <? extends Object> means that the Collection could be parameterized by all subclasses of the Object class and by the Object class itself
  • You couldn't use wildcards in the new instance instantiation (this will give compile error: new ArrayList<? extends Object>())
  • You could use the wildcards in variable declaration: List <? extends Object> list, the same as declaration of method variables
  • You could use wild cards when declaring the returning type of the method
  •  If variable is using: <? extends Object> this means that you won't add (or set) anything to this Collection
  •  If variable is using: <? super Object> you still could add to this Collection
  •  If you are writting <? super Number> it includes all super classer of number (here only Object class), but doesn't include the Number class itself
  • <? extends Object> is absolutely the same as <?>
  • To generify class you can write: class Foo T, and the use T as the generics type
  • You can use wildcards in class creation generics, but you can use question mark, the usage should look like class Foo<X extends Object>
  • If you create class like: class X <X> than the mentioned in the class X will be considered as the generic type
  • It is possible to use few generic types in one class, like: class Foo <X, Y>
  • You can generify the method will look like: <T> void T(){}. So the generic type should go exactly before the method return type
  • During overriding you could override the method that using generic return or input values with concrete classes, but the generic of child class should correctly set up with these concrete classes





No comments:

Post a Comment