Wednesday, 20 October 2010

Java Collections interview question

What is HashMap and Map? Map is Interface and Hashmap is class that implements this interface.

What is the significance of ListIterator?
Or
What is the difference b/w Iterator and ListIterator?
Iterator : Enables you to cycle through a collection in the forward direction only, for obtaining or removing elements
ListIterator : It extends Iterator, allow bidirectional traversal of list and the modification of elements
Difference between HashMap and HashTable? Can we make hashmap synchronized?
1. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
Note on Some Important Terms
1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
2)Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn’t modify the collection "structurally”. However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
HashMap can be synchronized by
Map m = Collections.synchronizeMap(hashMap);
What is the difference between set and list?
A Set stores elements in an unordered way and does not contain duplicate elements, whereas a list stores elements in an ordered way but may contain duplicate elements.
Difference between Vector and ArrayList? What is the Vector class?
Vector is synchronized whereas ArrayList is not. The Vector class provides the capability to implement a growable array of objects. ArrayList and Vector class both implement the List interface. Both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. In vector the data is retrieved using the elementAt() method while in ArrayList, it is done using the get() method. ArrayList has no default size while vector has a default size of 10. when you want programs to run in multithreading environment then use concept of vector because it is synchronized. But ArrayList is not synchronized so, avoid use of it in a multithreading environment.
What is an Iterator interface? Is Iterator a Class or Interface? What is its use?
The Iterator is an interface, used to traverse through the elements of a Collection. It is not advisable to modify the collection itself while traversing an Iterator.
What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
What is the List interface?
The List interface provides support for ordered collections of objects.
How can we access elements of a collection?
We can access the elements of a collection using the following ways:
1.Every collection object has get(index) method to get the element of the object. This method will return Object.
2.Collection provide Enumeration or Iterator object so that we can get the objects of a collection one by one.
What is the Set interface?
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.
What’s the difference between a queue and a stack?
Stack is a data structure that is based on last-in-first-out rule (LIFO), while queues are based on First-in-first-out (FIFO) rule.
What is the Map interface?
The Map interface is used associate keys with values.
What is the Properties class?
The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.
Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
a. Vector
b. ArrayList
c. LinkedList
d. None of the above
ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.
How can we use hashset in collection interface?
This class implements the set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the Null element.
This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.
What are differences between Enumeration, ArrayList, Hashtable and Collections and Collection?
Enumeration: It is series of elements. It can be use to enumerate through the elements of a vector, keys or values of a hashtable. You can not remove elements from Enumeration.
ArrayList: It is re-sizable array implementation. Belongs to 'List' group in collection. It permits all elements, including null. It is not thread -safe.
Hashtable: It maps key to value. You can use non-null value for key or value. It is part of group Map in collection.
Collections: It implements Polymorphic algorithms which operate on collections.
Collection: It is the root interface in the collection hierarchy.
What is difference between array & arraylist?
An ArrayList is resizable, where as, an array is not. ArrayList is a part of the Collection Framework. We can store any type of objects, and we can deal with only objects. It is growable. Array is collection of similar data items. We can have array of primitives or objects. It is of fixed size. We can have multi dimensional arrays.
Array: can store primitive            ArrayList: Stores object only
Array: fix size                            ArrayList: resizable
Array: can have multi dimensional
Array: lang                                ArrayList: Collection framework
Can you limit the initial capacity of vector in java?
Yes you can limit the initial capacity. We can construct an empty vector with specified initial capacity
public vector(int initialcapacity)
What method should the key class of Hashmap override?
The methods to override are equals() and hashCode().
What is the difference between Enumeration and Iterator?
The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects.
So Enumeration is used when ever we want to make Collection objects as Read-only.

Tuesday, 19 October 2010

Parsing Strings with split

parsing
dividing a string into tokens based on the given delimiters
token
one piece of information, a "word"
delimiter
one (or more) characters used to separate tokens
When we have a situation where strings contain multiple pieces of information (for example, when reading in data from a file on a line-by-line basis), then we will need to parse (i.e., divide up) the string to extract the individual pieces.

When there is just one character used as a delimiter

Example 1

We want to divide up a phrase into words where spaces are used to separate words. For example
the music made   it   hard      to        concentrate
In this case, we have just one delimiter (space) and consecutive delimiters (i.e., several spaces in a row) should be treated as one delimiter. To parse this string in Java, we do
String phrase = "the music made   it   hard      to        concentrate";
String delims = "[ ]+";
String[] tokens = phrase.split(delims);
Note that
  • the general form for specifying the delimiters that we will use is "[delim_characters]+" . (This form is a kind of regular expression. You don't need to know about regular expressions - just use the template shown here.) The plus sign (+) is used to indicate that consecutive delimiters should be treated as one.
  • the split method returns an array containing the tokens (as strings).  To see what the tokens are, just use a for loop:
    for (int i = 0; i < tokens.length; i++)
    System.out.println(tokens[i]);
    You should find that there are seven tokens: the, music, made, it, hard, to, concentrate

Example 2

Suppose each string contains an employee's last name, first name, employee ID#, and the number of hours worked for each day of the week, separated by commas. So
Smith,Katie,3014,,8.25,6.5,,,10.75,8.5
represents an employee named Katie Smith, whose ID was 3014, and who worked 8.25 hours on Monday, 6.5 hours on Tuesday, 10.75 hours on Friday, and 8.5 hours on Saturday. In this case, we have just one delimiter (comma) and consecutive delimiters (i.e., more than one comma in a row) should not be treated as one.  To parse this string, we do
String employee = "Smith,Katie,3014,,8.25,6.5,,,10.75,8.5";
String delims = "[,]";
String[] tokens = employee.split(delims);
After this code executes, the tokens array will contain ten strings (note the empty strings): "Smith", "Katie", "3014", "", "8.25", "6.5", "", "", "10.75", "8.5"
There is one small wrinkle to be aware of (regardless of how consecutive delimiters are handled): if the string starts with one (or more) delimiters, then the first token will be the empty string ("").

When there are several characters being used as delimiters

Example 3

Suppose we have a string containing several English sentences that uses only commas, periods, question marks, and exclamation points as punctuation.  We wish to extract the individual words in the string (excluding the punctuation).  In this situation we have several delimiters (the punctuation marks as well as spaces) and we want to treat consecutive delimiters as one
String str = "This is a sentence.  This is a question, right?  Yes!  It is.";
String delims = "[ .,?!]+";
String[] tokens = str.split(delims);
All we had to do was list all the delimiter characters inside the square brackets ( [ ] ).

Example 4

Suppose we are representing arithmetic expressions using strings and wish to parse out the operands (that is, use the arithmetic operators as delimiters).  The arithmetic operators that we will allow are addition (+), subtraction (-), multiplication (*), division (/), and exponentiation (^) and we will not allow parentheses (to make it a little simpler).  This situation is not as straight-forward as it might seem.  There are several characters that have a special meaning when they appear inside [ ].  The characters are ^  -  [  and two &s in a row(&&). In order to use one of these characters, we need to put \\ in front of the character:
String expr = "2*x^3 - 4/5*y + z^2";
String delims = "[+\\-*/\\^ ]+"; // so the delimiters are: + - * / ^ space
String[] tokens = expr.split(delims);

General template for using split

String s = string_to_parse;
String delims = "[delimiters]+"; // use + to treat consecutive delims as one;
// omit to treat consecutive delims separately
String[] tokens = s.split(delims);

java.util.StringTokenizer

The java.util.StringTokenizer class is used to break strings into tokens (words, numbers, operators, or whatever).
Has been replaced by regular expression tools. A more powerful solution is to use regular expressions, and the easiest way to do that is use the java.util.Scaner class, the String split(..) method, or the Pattern and Matcher classes.
A StringTokenizer constructor takes a string to break into tokens and returns a StringTokenizer object for that string. Each time its nextToken() method is called, it returns the next token in that string. If you don't specify the delimiters (separator characters), blanks are the default.

Constructors

StringTokenizer st = new StringTokenizer(s);
Creates a StringTokenizer for the String s that uses whitespace (blanks, tabs, newlines, returns, form feeds) as delimiters.
StringTokenizer st = new StringTokenizer(s, d);
Creates a StringTokenizer for the String s using delimiters from the String d.
StringTokenizer st = new StringTokenizer(s, d, f);
Creates a StringTokenizer for the String s using delimiters from the String d. If the boolean f is true, each delimiter character will also be returned as a token.

Common Methods

Assume that st is a StringTokenizer.
  • st.hasMoreTokens() -- Returns true if there are more tokens.
  • st.nextToken() -- Returns the next token as a String.
  • st.countTokens() -- Returns the int number of tokens. This can be used to allocate an array before starting, altho it can be inefficient for long strings because it has to scan the string once just to get this number. Using a Vector and converting it to an array at the end may be a better choice. 

Example: Find the longest word in a String

This code finds the longest word (characters separated by delimiter characters) in the String s, using blanks, commas, and tabs as delimiters.
// Assume s contains a string of words
String longestWord = "";
StringTokenizer st = new StringTokenizer(s, " ,\t");
while (st.hasMoreTokens()) {
String w = st.nextToken();
if (w.length() > longestWord.length()) {
longestWord = w;
}
}

Method overriding in java

Method hiding in java
public abstract class BaseClass {

 
public void insert(Object object) {
 
// Do something
 
}
}
 
public class SampleClass extends BaseClass {

 
public void insert(Object object, Long param){
 
// Do Something
 
}
}
SampleClass sampleClass = new SampleClass();
sampleClass
.insert(Object object);
sampleClass
.insert(Object object, Long param);
SampleClass sampleClass = new SampleClass();
sampleClass
.insert(Object object, Long param);
 
here is no way of hiding the method. You can do this:

@Override
public void insert(Object ob) {
 
throw new UnsupportedOperationException("not supported");
}

but that's it.
The base class creates a contract. All subclasses are bound by that contract. Think about it this way:
BaseObject b = new SomeObjectWithoutInsert();
b
.insert(...);
How is that code meant to know that it doesn't have an insert(Object) method? It can't.
Your problem sounds like a design problem. Either the classes in question shouldn't be inheriting from the base class in question or that base class shouldn't have that method. Perhaps you can take insert() out of that class, move it to a subclass and have classes that need insert(Object) extend it and those that need insert(Object, Object) extend a different subclass of the base object.

here is no way of hiding the method. You can do this:
@Override
public void insert(Object ob) {
 
throw new UnsupportedOperationException("not supported");
}
but that's it.
The base class creates a contract. All subclasses are bound by that contract. Think about it this way:
BaseObject b = new SomeObjectWithoutInsert();
b
.insert(...);
How is that code meant to know that it doesn't have an insert(Object) method? It can't.
Your problem sounds like a design problem. Either the classes in question shouldn't be inheriting from the base class in question or that base class shouldn't have that method. Perhaps you can take insert() out of that class, move it to a subclass and have classes that need insert(Object) extend it and those that need insert(Object, Object) extend a different subclass of the base object.



Static Methods
Can I override a static method? Many people have heard that you can't override a static method. This is true - you can't. However it is possible to write code like this:
class Foo {
    public static void method() {
        System.out.println("in Foo");
    }
}

class Bar extends Foo {
    public static void method() {
        System.out.println("in Bar");
    }
}
This compiles and runs just fine. Isn't it an example of a static method overriding another static method? The answer is no - it's an example of a static method hiding another static method. If you try to override a static method, the compiler doesn't actually stop you - it just doesn't do what you think it does.
So what's the difference?
Briefly, when you override a method, you still get the benefits of run-time polymorphism, and when you hide, you don't. So what does that mean? Take a look at this code:
class Foo {
    public static void classMethod() {
        System.out.println("classMethod() in Foo");
    }

    public void instanceMethod() {
        System.out.println("instanceMethod() in Foo");
    }
}

class Bar extends Foo {
    public static void classMethod() {
        System.out.println("classMethod() in Bar");
    }

    public void instanceMethod() {
        System.out.println("instanceMethod() in Bar");
    }
}

class Test {
    public static void main(String[] args) {
        Foo f = new Bar();
        f.instanceMethod();
        f.classMethod();
    }
}
If you run this, the output is
instanceMethod() in Bar
classMethod() in Foo
Why do we get instanceMethod from Bar, but classMethod() from Foo? Aren't we using the same instance f to access both of these? Yes we are - but since one is overriding and the other is hiding, we see different behavior. Since instanceMethod() is an instance method, in which Bar overrides the method from Foo, at run time the JVM uses the actual class of the instance f to determine which method to run. Although f was declared as a Foo, the actual instance we created was a new Bar(). So at runtime, the JVM finds that f is a Bar instance, and so it calls instanceMethod() in Bar rather than the one in Foo. That's how Java normally works for instance methods.
With classMethod() though. since it's a class method, the compiler and JVM don't expect to need an actual instance to invoke the method. And even if you provide one (which we did: the instance referred to by f) the JVM will never look at it. The compiler will only look at the declared type of the reference, and use that declared type to determine, at compile time, which method to call. Since f is declared as type Foo, the compiler looks at f.classMethod() and decides it means Foo.classMethod. It doesn't matter that the instance reffered to by f is actually a Bar - for static methods, the compiler only uses the declared type of the reference. That's what we mean when we say a static method does not have run-time polymorphism.
Because instance methods and class methods have this important difference in behavior, we use different terms - "overriding" for instance methods and "hiding" for class methods - to distinguish between the two cases. And when we say you can't override a static method, what that means is that even if you write code that looks like it's overriding a static method (like the first Foo and Bar at the top of this page) - it won't behave like an overridden method.
So what about accessing a static method using an instance?
It's possible in Java to write something like:
f.classMethod();
where f is an instance of some class, and classMethod() is a class method (i.e. a static method) of that class. This is legal, but it's a bad idea because it creates confusion. The actual instance f is not really important here. Only the declared type of f matters. That is, what class is f declared to be? Since classMethod() is static, the class of f (as determined by the compiler at compile time) is all we need.
Rather than writing:
f.classMethod();
It would be better coding style to write either:
Foo.classMethod();
or
Bar.classMethod(); 
That way, it is crystal clear which class method you would like to call. It is also clear that the method you are calling is indeed a class method. o;'oi;'i Barring that, you could always come up with this monstrosity:
f.getClass().getMethod("classMethod", new Class[]).invoke(null, new Object[]);
But all this could be avoided by simply not trying to override your static (class) methods. :-)
Why does the compiler sometimes talk about overriding static methods?
Sometimes you will see error messages from the compiler that talk about overriding static methods. Apparently, whoever writes these particular messages has not read the Java Language Specification and does not know the difference between overriding and hiding. So they use incorrect and misleading terminology. Just ignore it. The Java Language Specification is very clear about the difference between overriding and hiding, even if the compiler messages are not. Just pretend that the compiler said "hide" rather than "override"..
 


 
Java exceptions and function overriding.
   

Method overriding in java

Method overriding in java

Monday, 18 October 2010

Immutable objects

An immutable object is an object which state is guaranteed to stay identical over its entire lifetime. While it is perfectly possible to implement immutability without final, its use makes that purpose explicit, to the human (the software developer) and the machine (the compiler).
Immutable objects carry some very desirable characteristics:
  • they are simple to understand and easy to use
  • they are inherently thread-safe: they require no synchronization
  • they make great building blocks for other objects
Clearly final is going to help us define immutable objects. First in labelling our object as immutable, which makes it simple to use and understand by other programmers. Second in guaranteeing that the object's state never changes, which enable the thread-safe property: thread concurrency issues are relevant when one thread can change data while another thread is reading the same data. Because an immutable object never changes its data, synchronizing access to it is not needed. Create an immutable class by meeting all of the following conditions:
  1. Declare all fields private final.
  2. Set all fields in the constructor.
  3. Don't provide any methods that modify the state of the object; provide only getter methods (no setters).
  4. Declare the class final, so that no methods may be overridden.
  5. Ensure exclusive access to any mutable components, e.g. by returning copies.