Wednesday, August 15, 2012

Natural Order


Natural order

Classes Implementing Comparable
Class
Natural Ordering
Byte
Signed numerical
Character
Unsigned numerical
Long
Signed numerical
Integer
Signed numerical
Short
Signed numerical
Double
Signed numerical
Float
Signed numerical
BigInteger
Signed numerical
BigDecimal
Signed numerical
Boolean
Boolean.FALSE < Boolean.TRUE
File
System-dependent lexicographic on path name
String
Lexicographic
Date
Chronological
CollationKey
Locale-specific lexicographic

java Collection classes


Core implementation classes in Collection Framework

Maps
Sets
Lists
Queues
Utilities
HashMap
HashSet
ArrayList
PriorityQueue
Collections
Hashtable
LinkedHashSet
Vector

Arrays
TreeMap
TreeSet
LinkedList


LinkedHashMap

Stack


Collection and Map Hierarchy




Map Hierarchy

                                    

Tuesday, August 14, 2012

Java Collections FAQ


Java Collections overview: The topic that covers most part of the interview.I will provide questions I faced in my 8 years of experience.

1) Why should be override hashCode() and equals()?.

     Even though not a part of Collections.Most of the collections internally use these methods for their functionality.So this is a stock question asked by almost all interviewers.

equals() is used in HashMap,HashTable for keys and even in Set.If you don't override equals() you cant use them in above collections and many other.If you override equals just be sure that you override hashcode() method also.So to compare 2 objects based on their state and attributes and by not its identity(address bits) we should override equals and hashcode.

2) What is the need to overide equals and hashcode ,both all the time?

    equals and hashcode are bound by a joint contract that specifies if 2 objects are equal then their hashcodes should be identical.Not necessarily the other way round.(From Java specification).

3) What do we need to override hashcode and where is it used in java?.

     Collections such as HashMap,HashSet and HashTable use hashcode to determine how to store and retrieve the object in a collection.

4) How is hashtable implemented?.

     HashTable uses buckets to fill in the objects(keys) and each bucket will be identified by an identifier(hashcode) calculated using the key(object). The process of storing and retrieving objects is a 2 step process.

  1. Find the right bucket (using hashcode()).
  2. Search the bucket for the right element (using equals()).   
5) Can different objects have the same hashcode or can I give 15 as a constant hashcode?

     Yes,you can have a constant hashcode but then the search in collections will degenerate to a linear search(based on implementation).

6) How to implement a good hashcode()?

     Basic logic is to use all the instance variables used in the equals method of the same object.Other than that you can use any legal implementation.

7) If 2 hashcodes are not equal ,then calling equal on those objects return true or false?

    false,If 2 hashcodes are equal then the equals need not return true,but if 2 hashcodes are not equal then the 2 objects also should be not equal.

i.e if x.hashcode() != y.hashcode() then x.equals(y) == false;

8) Can I use transient variables in equals and hashcode?.

     No(but compiler will not complain if you use the same),transient variables after deserialization will be initialized to default values.So the state is not saved on serialization and the computed hashcode will be different on deserialization thus breaking the equlas hashcode contract.

9) Can I change an object state which is used as a key in a hashtable(the key is in the table)?.

    Yes you can change,but changing the variable state or values will change the equality of the objects and on search you might not find the value.So it is always advised to use immutable objects as keys i.e Strings or Wrapper classes.

10)   How to make a class immutable?

    Make a class immutable by following these guidelines :
  • ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
  • make fields private and final
  • force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods (that is, avoid the Java Beans convention)
  • do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state
  • if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller
11) What are collections in Java?.

     Collections are datastructure implementations provided by java for the programmer to use directly without reinventing the wheel.Collections can be used for the following operations.
  1. Add objects to the collection
  2. Remove objects from the collection
  3. Find if an object is in the collection.
  4. Retrieve an object from a collection.
  5. Iterate through the collection.
12) What are the key interfaces and classes in Collections Framework?.

     Core Interfaces are
  1. Collection
  2. List
  3. Queue
  4. Set
  5. SortedSet
  6. Map
  7. SortedMap
  8. NavigableSet
  9. NavigableMap 
13) What is the base interface of all collections?

    Collection and Map,

14) Does collection extends any other interface?If so what is the interface?.

   Yes, Iterable is the interface,with only a single method Iterator<T> iterator()

15) Why do we need to extend Iterator interface in Collections?From which version of Java this interface is introduced?.

    Implementing this interface allows an object to be the target of the "foreach" statement.From version 1.5



Note: you can find the hierarchy here Collection and Map Hierarchy
   
Note: Important classes in Collection Framework Collection classes 


16) Name the collection class which implements both List and Queue interfaces?.

      LinkedList [API]

17) Is SortedSet a class or interface?

      Interface [API]

18) What is meant by ordered collections?

      A collection can be an Ordered collection or Unordered collection.A collection is said to be ordered if you can iterate through the collection in a specific order(not-random).Ex:
  • A Hashtable is unordered.
  • ArrayList maintains order based on index.
  • LinkedHashSet maintains the insertion order.
  • TreeSet maintains the natural ordering of the elements.
19) What is a Sorted Collection?

      A Sorted collection means that the order in the collection is determined according to some rules ,known  as sort order.Sorting is based on the properties of the elements not based on the attributes like when the element is added,access time or position.

20) What is Natural order of a Collection and how is different from Sort order?.

     Most of the time the natural order is the sort order.For Strings the natural order is alphabetical order.Some of the classes have already implemented natural ordering.[Natural Order].

We can define the natural order of an object/element by implementing an interface Comparable[API].

21) What is Comparable and why is it used?.

    This interface imposes a total ordering on the objects of each class that implements it.This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.The classes which implement this interface can be directly used in Collections.sort(List)/Arrays.sort(Object[]).

22) Should the natural order of an element be consistent with equals?If yes, then why?.

     Yes, The natural ordering of a class C are said to consistent with equals if obj1.compareTo(obj2) == 0 has the same boolean value as obj1.equals(obj2) for every object obj1 and obj2 of a class C.


     




   

Monday, August 13, 2012

FAQ in Java/J2EE updated daily

Recently one of my colleague had problems loading values from a property file.He analyzed the problem and emphasized that having spaces in the key is creating problems.We have to remove all the spaces in the properties file keys to satisfy him.The problem persisted..

Based on this I would like to provide some basic theory and Q and A on Properties.

1) How to load properties files in Java?.

    Option 1: We can load using absolute file paths or relative file paths.Using absolute file paths is not portable and relative files are resolved based on the JVM directory which users might have control in production.We normally should not use files API to access resources to be platform independent.

   Option 2: Using a property file as a classpath resource.Recommended way to load a resource and is portable.

2) Can we have default values for the properties in java?.

     From the API 'A property list can contain another property list as its "defaults"; this second property list is searched if the property key is not found in the original property list'.So yes but using java API and not in the file.

Properties(Properties defaults) 
          Creates an empty property list with the specified defaults.

or

getProperty(String key, String defaultValue) 
          Searches for the property with the specified key in this property list.


3) Can we use Unicode characters in properties files?

      No,in properties the input/output stream is encoded in ISO 8859-1 character encoding.

4) How can we read Unicode data from properties file?.

      Characters that cannot be directly represented in this encoding can be written using Unicode escapes only a single 'u' character is allowed in an escape sequence. The native2ascii tool can be used to convert property files to and from other character encodings.(From the API).


In Java 1.6 you can use other encodings by using the methods that use Reader/Writer instead of InputStream/OutputStream

Sample: In Java 1.6

Properties props = new Properties();
URL resource = getClass().getClassLoader().getResource("data.properties");         
props.load(new InputStreamReader(resource.openStream(), "UTF8"));




5) How to read properties from properties in java?.

     Use any of the method to get the stream

     ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
     Class.getResourceAsStream ("/some/pkg/resource.properties");
     ResourceBundle.getBundle ("some.pkg.resource");


   
Method
Parameter format
Lookup failure behavior
Usage example
ClassLoader.
getResourceAsStream()
"/"-separated names; no leading "/" (all names are absolute)
Silent (returns null)
this.getClass().getClassLoader()
.getResourceAsStream
("some/pkg/resource.properties")
Class.
getResourceAsStream()
"/"-separated names; leading "/" indicates absolute names; all other names are relative to the class's package
Silent (returns null)
this.getClass()
.getResourceAsStream
("resource.properties")
ResourceBundle.
getBundle()
"."-separated names; all names are absolute;.properties suffix is implied
Throws unchecked
java.util.MissingResourceException
ResourceBundle.getBundle
("some.pkg.resource")
   
     after retrieving the input stream we can load the same into a property object using

     Properties prop = new Properties();
     prop.load(inputStream);

6) Are leading and training spaces considered part of the key in properties?.

     No, from the API Any white space after the key is skipped; if the first non-white space character after the key is '=' or ':', then it is ignored and any white space characters after it are also skipped.

Example : As an example, each of the following three lines specifies the key "Truth" and the associated element value "Beauty"
Truth = Beauty
        Truth:Beauty
 Truth                  :Beauty

7) Can I have only a key in property file without the value?.
     Yes,and the value will be an empty string by default.

8) Can I load properties from an XML file?.

      Yes,we can load an XML file using the method,By default the UTF-8 characterencoding is used,however a specific encoding may be specified if required.
 public void loadFromXML(InputStream in)

 and the DTD should be of the following format

 <?xml version="1.0" encoding="UTF-8"?>
 <!-- DTD for properties -->

 <!ELEMENT properties ( comment?, entry* ) >

 <!ATTLIST properties version CDATA #FIXED "1.0">

 <!ELEMENT comment (#PCDATA) >

 <!ELEMENT entry (#PCDATA) >

 <!ATTLIST entry key CDATA #REQUIRED>

9) Can we save a modified properties to the file?.
     Yes, using store or storeToXML.

10) Is the Properties class thread-safe,can multiple threads access the properties safety?.

     Yes. (From the API: This class is thread-safe: multiple threads can share a single Properties object without the need for external synchronization)

11) What is the super class of Properties?.

    HashTable.

12) Is Properties Serializable or Cloneable?.
    Both.