Showing posts with label Java Basic. Show all posts
Showing posts with label Java Basic. Show all posts

Creating Custom Annotations and Making Use of Them



How to Create a Custom Annotations?Read full article from 
public @interface Copyright {
   String info() default "";
}
Since we didn't define any @Target , you can use this annotation anywhere in your classes by default. If you want your annotation to be only available for class-wise or method-wise, you should define @Target annotation. 
annotations are interfaces, so you don't implement anything in them.
How to Make Use of Your Custom Annotations?
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
   Class expected();
}
@Retention marks our annotation to be retained by JVM at runtime. This will allow us to use Java reflections later on.
Test test = method.getAnnotation(Test.class);
// we use Class type here because our attribute type
// is class. If it would be string, you'd use string
Class expected = test.expected();
try {
   method.invoke(null);
   pass++;
} catch (Exception e) {
   if (Exception.class != expected) {
       fail++;
   } else {
       pass++;
   }
}

Creating Custom Annotations and Making Use of Them

http://stackoverflow.com/questions/960431/how-to-convert-listinteger-to-int-in-java



In addition to Commons Lang, you can do this with Guava's method Ints.toArray(Collection<Integer> collection).
List<Integer> list = ...  int[] ints = Ints.toArray(list);
List<Integer> Ints.asList(int...)
The easiest way to do this is to make use of Apache Commons Lang. It has a handy ArrayUtils class that can do what you want. Use the toPrimitive method with the overload for an array of Integers.
List<Integer> myList;
 ... assign and fill the list
int[] intArray = ArrayUtils.toPrimitive(myList.toArray(new Integer[myList.size()]));
Unfortunately, I don't believe there really is a better way of doing this due to the nature of Java's handling of primitive types, boxing, arrays and generics. In particular:
  • List<T>.toArray won't work because there's no conversion from Integer to int
  • You can't use int as a type argument for generics, so it would have to be an int-specific method (or one which used reflection to do nasty trickery).
Read full article from http://stackoverflow.com/questions/960431/how-to-convert-listinteger-to-int-in-java

What is Iterator and ListIterator



public interface Iterator<E> {
    E next();
    void remove();
}
JDK8 Iterator interfaces add default implementation for remove method and add another method: forEachRemaining with default method.
public interface Enumeration<E> {
    boolean hasMoreElements();
    E nextElement();
}
Why use Iterator when we have Enumerator:
Both Iterator and Enumerator is used for traversing of collection but Iterator is more enhanced in terms of extra method remove () it provide us for modify the collection which is not available in enumeration
What is List Iterator in Java?
interface ListIterator<E> extends Iterator<E>
{
  boolean hasNext();
  E next();
  boolean hasPrevious();
  E previous();
  int nextIndex();
  int previousIndex();
  void remove();
  void set(E paramE);
  void add(E paramE);
}
ListIterator in Java is an Iterator which allows user to traverse Collection like ArrayList and HashSet in both direction by using method previous() and next ().
2) If you want to remove objects from Collection than don't use for-each loop instead use Iterator's remove() method to avoid any ConcurrentModificationException.
3) Iterating over collection using Iterator is subject to ConcurrentModificationException if Collection is modified after Iteration started, but this only happens in case of fail-fast Iterators.
4) There are two types of Iterators in Java, fail-fast and fail-safe.
5) List collection type also supports ListIterator which has add() method to add elements in collection while Iterating.
Read full article from What is Iterator and ListIterator in Java Program with Example - Tutorial Code Sample

Learning From Code: Fast Random Access



Marker interfaces do not define behavior directly, instead they "mark" a class as having a particular capability. In the case of Serializable the interface specifies that if the class is serialized using the serialization I/O classes, then a NotSerializableException will not be thrown (unless the object contains some other class that cannot be serialized). Cloneable similarly indicates that the use of the Object.clone() method for a Cloneable class will not throw a CloneNotSupportedException.
The RandomAccessinterface identifies that a particular java.util.List implementation has fast random access. More accurately, the RandomAccess interface identifies List implementations which are faster to iterate using the List.get() method rather than using the Iterator.next() method.
However, when you want to iterate List classes, then you can optimize the iteration speed by using RandomAccess
Many of the utility methods in Collections class use a variant of an algorithm depending on whether or not the object is a RandomAccess object.
    public static int binarySearch(List list, Object key) {
        if (list instanceof RandomAccess || list.size() < BINARYSEARCH_THRESHOLD)
            return indexedBinarySearch(list, key);
        else
            return iteratorBinarySearch(list, key);
    }

   public static void fill(List list, Object obj) {
        int size = list.size();


        if (size <  FILL_THRESHOLD || list instanceof RandomAccess) {
            for (int i=0; i< size; i++)
                list.set(i, obj);
        } else {
            ListIterator itr = list.listIterator();
            for (int i=0; i< size; i++) {
                itr.next();
                itr.set(obj);
            }
        }
    }
Read full article from Learning From Code: Fast Random Access, page 1 of 2

40 Java Collections Interview Questions and Answers | Java Code Geeks



What is difference between fail-fast and fail-safe?

Iterator fail-safe property work with the clone of underlying collection, hence it’s not affected by any modification in the collection. By design, all the collection classes in java.util package are fail-fast whereas collection classes in java.util.concurrent are fail-safe. Fail-fast iterators throw ConcurrentModificationException whereas fail-safe iterator never throws 

How to avoid ConcurrentModificationException while iterating a collection?

We can use concurrent collection classes to avoid ConcurrentModificationException while iterating over a collection, for example CopyOnWriteArrayList instead of ArrayList.

What is Comparable and Comparator interface?

Java provides Comparable interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods. Comparable interface has compareTo(T obj) method which is used by sorting methods. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if “this” object is less than, equal to, or greater than the object passed as argument.
But, in most real life scenarios, we want sorting based on different parameters.  This is the situation where we need to use Comparator interface because Comparable.compareTo(Object o)method implementation can only sort based on predefined fields or logic and we can’t chose the field on which we want to sort the Object.Comparator interface compare(Object o1, Object o2) method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if first argument is less than the second one and returns zero if they are equal and positive int if first argument is greater than second one.

How can we sort a list of Objects?

If we need to sort an array of Objects, we can use Arrays.sort(). If we need to sort a list of objects, we can useCollections.sort(). Both these classes have overloaded sort() methods for natural sorting (using Comparable) or sorting based on criteria (using Comparator). Collections internally uses Arrays sorting method, so both of them have same performance except that Collections take sometime to convert list to array.

What are best practices related to Java Collections Framework?

  • Chosing the right type of collection based on the need, for example if size is fixed, we might want to use Array over ArrayList. If we have to iterate over the Map in order of insertion, we need to use TreeMap. If we don’t want duplicates, we should use Set.
  • Some collection classes allows to specify the initial capacity, so if we have an estimate of number of elements we will store, we can use it to avoid rehashing or resizing.
  • Write program in terms of interfaces not implementations, it allows us to change the implementation easily at later point of time.
  • Always use Generics for type-safety and avoid ClassCastException at runtime.
  • Use immutable classes provided by JDK as key in Map to avoid implementation of hashCode() and equals() for our custom class.
  • Use Collections utility class as much as possible for algorithms or to get read-only, synchronized or empty collections rather than writing own implementation. It will enhance code-reuse with greater stability and low maintainability
Read full article from 40 Java Collections Interview Questions and Answers | Java Code Geeks

What is EnumMap in Java - Example Tutorial



EnumMap is optimized Map implementation exclusively for enum keys
1. All keys used in EnumMap must be  from same Enum type which is specified while creating EnumMap in Java. For example if you can not use different enum instances from two different enum.
2. EnumMap is ordered collection and they are maintained in the natural order of their keys( natural order of keys means  the order on which enum constant are declared inside enum type ). you can verify this while Iterating over an EnumMap in Java.
3. Iterators of EnumMap are fail-fast Iterator , much like of ConcurrentHashMap and doesn't throw ConcurrentModificationException and may not show effect of any modification on EnumMap during Iteration process.
4. You can not insert null keys inside EnumMap in Java.  EnumMap doesn't allow null key and throw NullPointerException, at same time null values are permitted.
5. EnumMap is not synchronized and it has to be synchronized manually before using it in a concurrent or multi-threaded environment. like synchronized Map in Java  you can also make EnumMap synchronized by using Collections.synchronizedMap() method and as per javadoc this should be done while creating EnumMap in java to avoid accidental non synchronized access.
6. EnumMap is likely give better performance than HashMap in Java. So prefer EnumMap if you are going to use enum keys.

Read full article from What is EnumMap in Java – Example Tutorial

EnumSet in Java - RegularEnumSet vs JumboEnumSet



When to use EnumSet in Java

This item advises us to use EnumSet in the place of bit fields, which is part of enum int pattern.
  1. EnumSet can only be created of a single enum type, which means you can not create EnumSet of Month and DayOfWeek together.
  2. EnumSet doesn't allow null elements. Attempting to insert null on EnumSet will throwNullPointerException.
  3. EnumSet is not thread-safe, which means if it needs to be externally synchronized, when multiple threads access it and one of them modifies the collection.
  4. Iterator of EnumSet is fail-safe and weakly consistent, which means noConcurrentModificationException. Also traversing order of Iterator is defined by natural ordering of Enum, and it may or may not show result of any modification done during iteration.
  5. EnumSet is a high performance Java Collection. It provides O(1) performance for add(),contains() and next() operations because of array based access. Preferably, useEnumSet over HashSet for storing Enum constants.
Read full article from EnumSet in Java - RegularEnumSet vs JumboEnumSet

Difference between RegularEnumSet and JumboEnumSet in Java | Java67



Since Enum always has fixed number of instances, data-structure which is used to store Enum can be optimized depending upon number of instances

How EnumSet is implemented in Java

EnumSet is an abstract class and it provides two concrete implementations, java.util.RegularEnumSet and java.util.JumboEnumSet. Main difference between RegularEnumSet and JumboEnumSet is that former uses a long variable to store elements while later uses a long[] to store its element.  Since RegularEnumSet uses long variable, which is a 64 bit data type, it can only hold that much of element. That's why when an empty EnumSet is created using EnumSet.noneOf() method, it choose RegularEnumSet if key universe (number of enum instances in Key Enum) is less than or equal to 64 and JumboEnumSet if key universe is more than 64.

From: EnumSet in Java - RegularEnumSet vs JumboEnumSet
  1. EnumSet can only be created of a single enum type, which means you can not create EnumSet of Month and DayOfWeek together.
  2. EnumSet doesn't allow null elements. Attempting to insert null on EnumSet will throwNullPointerException.
  3. EnumSet is not thread-safe, which means if it needs to be externally synchronized, when multiple threads access it and one of them modifies the collection.
  4. Iterator of EnumSet is fail-safe and weakly consistent, which means noConcurrentModificationException. Also traversing order of Iterator is defined by natural ordering of Enum, and it may or may not show result of any modification done during iteration.
  5. EnumSet is a high performance Java Collection. It provides O(1) performance for add(),contains() and next() operations because of array based access. Preferably, useEnumSet over HashSet for storing Enum constants.
.Beauty of EnumSet implementation lies on how they are created. This class is purposefully made package-private so that no one can create instance of EnumSet. you can only create instance of EnumSet by using different factory methods provided by API. This allows API to choose from RegularEnumSet and JumboEnumSet, depending upon number of instances of Enum i.e. key size. This arrangement is also very extensible and manageable because you can introduce new EnumSet implementation without breaking client code.
RegularEnumSet
    public boolean add(E e) {
        typeCheck(e);
        long oldElements = elements;
        elements |= (1L << ((Enum)e).ordinal());
        return elements != oldElements;
    }
    public boolean remove(Object e) {
        if (e == null)
            return false;
        Class eClass = e.getClass();
        if (eClass != elementType && eClass.getSuperclass() != elementType)
            return false;
        long oldElements = elements;
        elements &= ~(1L << ((Enum)e).ordinal());
        return elements != oldElements;
    }
JumboEnumSet
class JumboEnumSet<E extends Enum<E>> extends EnumSet<E> {
    /**
     * Bit vector representation of this set.  The ith bit of the jth
     * element of this array represents the  presence of universe[64*j +i]
     * in this set.
     */
    private long elements[];
    public boolean add(E e) {
        typeCheck(e);

        int eOrdinal = e.ordinal();
        int eWordNum = eOrdinal >>> 6;

        long oldElements = elements[eWordNum];
        elements[eWordNum] |= (1L << eOrdinal);
        boolean result = (elements[eWordNum] != oldElements);
        if (result)
            size++;
        return result;
    }
    public boolean remove(Object e) {
        if (e == null)
            return false;
        Class eClass = e.getClass();
        if (eClass != elementType && eClass.getSuperclass() != elementType)
            return false;
        int eOrdinal = ((Enum)e).ordinal();
        int eWordNum = eOrdinal >>> 6;

        long oldElements = elements[eWordNum];
        elements[eWordNum] &= ~(1L << eOrdinal);
        boolean result = (elements[eWordNum] != oldElements);
        if (result)
            size--;
        return result;
    }
Read full article from Difference between RegularEnumSet and JumboEnumSet in Java | Java67

Labels

Algorithm (219) Lucene (130) LeetCode (97) Database (36) Data Structure (33) text mining (28) Solr (27) java (27) Mathematical Algorithm (26) Difficult Algorithm (25) Logic Thinking (23) Puzzles (23) Bit Algorithms (22) Math (21) List (20) Dynamic Programming (19) Linux (19) Tree (18) Machine Learning (15) EPI (11) Queue (11) Smart Algorithm (11) Operating System (9) Java Basic (8) Recursive Algorithm (8) Stack (8) Eclipse (7) Scala (7) Tika (7) J2EE (6) Monitoring (6) Trie (6) Concurrency (5) Geometry Algorithm (5) Greedy Algorithm (5) Mahout (5) MySQL (5) xpost (5) C (4) Interview (4) Vi (4) regular expression (4) to-do (4) C++ (3) Chrome (3) Divide and Conquer (3) Graph Algorithm (3) Permutation (3) Powershell (3) Random (3) Segment Tree (3) UIMA (3) Union-Find (3) Video (3) Virtualization (3) Windows (3) XML (3) Advanced Data Structure (2) Android (2) Bash (2) Classic Algorithm (2) Debugging (2) Design Pattern (2) Google (2) Hadoop (2) Java Collections (2) Markov Chains (2) Probabilities (2) Shell (2) Site (2) Web Development (2) Workplace (2) angularjs (2) .Net (1) Amazon Interview (1) Android Studio (1) Array (1) Boilerpipe (1) Book Notes (1) ChromeOS (1) Chromebook (1) Codility (1) Desgin (1) Design (1) Divide and Conqure (1) GAE (1) Google Interview (1) Great Stuff (1) Hash (1) High Tech Companies (1) Improving (1) LifeTips (1) Maven (1) Network (1) Performance (1) Programming (1) Resources (1) Sampling (1) Sed (1) Smart Thinking (1) Sort (1) Spark (1) Stanford NLP (1) System Design (1) Trove (1) VIP (1) tools (1)

Popular Posts