Knowledge Transfer

Ethickfox kb page with all notes


Project maintained by ethickfox Hosted on GitHub Pages — Theme by mattgraham

Managing Objects





Lambdas


Streams


Methods


Do not overload methods to take different interfaces of same hierarchy in the same argument position Differently from overriding it would invoke method based on compile-time information

  public class CollectionClassifier {  
      public static String classify(Set<?> s) {  
          return "Set";  
      }  
    
      public static String classify(List<?> lst) {  
          return "List";  
      }  
    
      public static String classify(Collection<?> c) {  
          return "Unknown Collection";  
      }  
    
      public static void main(String[] args) {  
          Collection<?>[] collections = {  
              new HashSet<String>(),  
              new ArrayList<BigInteger>(),  
              new HashMap<String, String>().values()  
          };  
    
          for (Collection<?> c : collections)  
           System.out.println(classify(c)); // `Unknown Collection` x3
      }  
  }

Consider using a custom serialized form when object’s physical representation is not identical to its logical content.

		// Not suitable for default serialization
		public final class StringList implements Serializable {  
		    private int size = 0;  
		    private Entry head = null;  
		  
		    private static class Entry implements Serializable {  
		        String data;  
		        Entry  next;  
		        Entry  previous;  
		    }  

		    private void writeObject(ObjectOutputStream s) {  
		        s.writeInt(size);  
		        for (Entry e = head; e != null; e = e.next)  
		            s.writeObject(e.data);  
		    } 
		}

Exceptions

// Invocation with checked exception 
try {  
    obj.action(args);  
} catch (TheCheckedException e) {  
    ... // Handle exceptional condition  
}
if (obj.actionPermitted(args)) {  
    obj.action(args);  
} else {  
    ... // Handle exceptional condition  
}

public Object pop() {  
    //if (size == 0)
    //    throw new EmptyStackException();
    Object result = elements[--size];// ArrayIndexOutOfBoundsException 
    elements[size] = null; 
    return result;  
}

public E get(int index) {  
    ListIterator<E> i = listIterator(index);  
    try {  
        return i.next();  
    } catch (NoSuchElementException e) {  
        throw new IndexOutOfBoundsException("Index: " + index);  
    }  
}

Concurrency