Java Collections - Part 5: Algorithms

Andromeda

This article is a part of the Java Programming Language article series.

  • Sorting
  • Shuffling
  • Routine Data Manipulation
  • Searching
  • Composition
  • Finding Extreme Values
  • Reorders a List in ascending order
  • Uses merge sort algorithm
  • The sort method:
    Collections.sort(list);
    Collections.sort(list, comparator);
  • The opposite of sort
  • In all possible permutations with equal likelihood
  • Useful in implementing games of chance
  • The shuffle method
    Collections.shuffle(list);
    Collections.shuffle(list, new Random());

reverse

  • Reverses the list order

fill

  • Overwrites list elements with the specified value
  • Useful for reinitializing

copy

  • Copies the elements
  • Destination and source arguments
  • Overwrites the contents
  • Destination list size must be equal or greater than source list size

swap

  • Swaps list elements at the specified positions

addAll

  • Adds all the collection elements
  • Searches for a list element
  • The binarySearch method
  • Returns index value

frequency

  • Counts the number of times the specified element occurs in the specified collection

disjoint

  • Determines two collections contain no elements in common
  • The min and the max methods

Compatibility

  • Interoperability between the core collection interfaces and the types that were used to represent collections in the early versions of the Java platform
    Vector, Hashtable, array, and Enumeration
  • Transform old collections to new collections and vice versa

API Design

  • Upward Compatibility
  • Backward Compatibility
  • Array to List
    Object[] objects;
    Arrays.asList(objects);
  • Vector to List
  • Hashtable to Map
  • Enumeration to Collection
    Enumeration enumeration;
    Collections.list(enumeration);
  • Collection to Array
    Collection collection;
    collection.toArray();
    (String[]) collection.toArray(new String[0]);
  • Collection to Vector
    Collection collection;
    new Vector(collection);
  • Map to Hashtable
    Map map;
    new Hashtable(map);
  • Collection to Enumeration
    Collection collection;
    Collections.enumeration(collection);

Parameters

  • Use interface types
  • Never use an implementation type
  • The best types to use on input are the most general
  • Collection and Map

Return Values

  • Return the most specific applicable collection interface rather than the most general

Legacy APIs

  • Define an adapter class that wraps the legacy collections objects

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store