Its bit wise operator ,which can be applied to the integer types, long, int, short, char, and byte. & (bitwise and) Binary AND Operator copies a bit to the result if it exists in both operands means & evaluates both sides of the operation.
Java Interview Question,Java tutorial and Java related Stuffs
Showing posts with label Java Interview Question. Show all posts
Showing posts with label Java Interview Question. Show all posts
Saturday, 18 June 2016
Remove special characters(?) from String.
\p{ASCII} is POSIX character classes.It will replace the non ascii string and return the string(Printable ASCII).
String string=givenString.replaceAll("[^\\p{ASCII}]", "");
Tuesday, 31 May 2016
Java Abstract class and interface Interview Questions
Below are the some question which are generally asked in Java interview question from Abstract class and interface.
Question-Can abstract class have constructor?
Yes,An abstract class can contain a constructor. An abstract class constructor is used to initialize fields of the abstract class. You could provide a constructor for an abstract class if you want to initialize specific fields of the abstract class before the instantiation of a child-class.We cannot create an instance of an abstract class, But we can create instances of classes those are derived from the abstract class. So, when an instance of derived class is created, the parent abstract class constructor will automatically get called.
Question-Can abstract class implements interface in Java? Is it necessary to implement all methods?
Yes, abstract class can implement the interface. When we implement an interface to an abstract class, its means that the abstract class inherited all the methods of the interface.
Its depend upon the class which is implementing the interface. When we implement an interface to an abstract class, then the abstract class inherited all the methods of the interface. As, it is not important to implement all the method in abstract class however it comes to abstract class , so the abstract class can left some of the method in interface without implementation. In concrete class we need to implement all the inherited method.
Question-Can we declare abstract class as final in Java?
No a class cannot be declare as "abstract" and "final" both. Declaring a class as "abstract" means it contains method definition and hence depends on its subclasses to provide concrete implementation.
Making a class "final" means that no other class can extend it and hence abstract classes cannot be marked final.
In short An abstract class must be sub-classed, whereas a final class must not be sub-classed.
An abstract class without being inherited is of no use and hence will result in compile time error.
Question-Can an abstract class have static methods in Java?
Yes, an abstract class can have static method. You cannot create an abstract static method, you can create a non abstract static method.
Reason is you do not need a object instance to access a static method because that method can be called directly, even if you do not have an instance of the abstract class.(to invoke static method you do not need to build a class instance (i.e object))
Question-is it possible to create a instance of abstract class in java?
No, its never possible to instantiate an abstract class. But might be interviewer can say “YES WE CAN” at that time as below,
abstract class myClass {
public void m1()
{System.out.print(“Inside Abstract class");}}
class implmentmyClass { public static void main(String a[]) { myClass m = new myClass () {};
m.m1(); }
}
The given code block in last page instantiates an anonymous inner class which is a subclass of the myClass abstract class. It is not same as instantiating the abstract class itself. we can use new keyword to create an anonymous class instance by just adding {} as implement body at the end of the abstract class. so its not the abstract class instantiation its anonymous class.
Question- Is it necessary for abstract class to have abstract method?
No, we can have an abstract class without Abstract Methods as both are independent. Declaring a class abstract means that it can not be instantiated on its own and can only be sub classed. Declaring a method abstract means that Method will be defined in the subclass. So you can easily define an abstract class without any abstract method.
Question- Can we define main method in abstract class?
Yes, we can define main method inside the abstract class, Loading a class is not the same as creating an instance/object of the class(using new operator). And there's no need to create an instance of the class to call main(), because it's static method. So there's no problem if we will define the main method inside an abstract class.
Question- Can you use abstract and final both with a method.
No, we can not declare abstract method as final. We have to provide implementation to abstract methods in subclasses, and if we will mark it as final then we can’t provide the method reimplementation for that final method in it’s derived classes.
final abstract int add(int n1,int n2);
Here we can’t provide the implementation for the add method as it is declared as final. But at the same time you declare it as abstract. Here we can’t provide the implementation for the add method. Even we described to provide implementation but we cant.
Question- Can you declare an interface method as static ?
NO, interface only contains abstract method.
Suppose we have a Test class with a static method add. we can call this as
Test.add(2, 3);
If Test were an interface instead of a class, it could not have any defined functions. As such, calling something like Test.add(2, 3) doesn't make any sense.
Question- Can we declare an Interface be final ?
No. We can not instantiate interfaces, so in order to make interfaces useful we must create subclasses. When the final keyword appears in a class declaration, it means that the class may never be subclassed or overridden. Interface represent behaviour, rather than implementation, therefore it makes no sense for it to be final.
Question- Can we define private and protected modifiers for variables in interfaces.
No we cant define the variable with private, protected in interface. only public, static & final are permitted with variable inside an interface. An interface provide a way for the client to interact with the object. If variables will not be public, the clients would not have access to them. that is why variable are public.
Question-Can we use “abstract” keyword with constructor?
No, we cant declare the constructor as abstract because abstract means we must have to override it in non abstract child class and you can not override a constructor. Constructors are not inherited thus we cannot override them.
Question-Can we declare abstract methods as private?
No. Abstract methods can not be private. we cant inherit the private method, so its doesn't make a sense to declare a private method abstract. Declaring a abstract method means we need to override and implement it in child/subclass, but we cant override private methods so we cant make it abstract. You can declare it protected instead of private.
Question-We can’t instantiate an abstract class. Then why constructors are allowed in abstract class?
The use of constructor to initialize the instance of classes. We use a constructor to create new object often with parameter specifying the initial value or other important information about the object. Suppose inside a class we have some fields we always want them to initialize, to do this we create a constructor and initialize them. If we have two different subclasses of abstract class when we instantiate them their constructor will get called and then parent constructor will get called and field will get initialized. Every constructor invokes the constructor of its super class with an implicit call to super.
Question-Abstract classes can be nested. True or false?
True, Abstract classes can be nested. A abstract nested classes are the inner classes marked with abstract modifier. Inner class acts as a member of the enclosing class and can have any access modifiers: abstract, final, public, protected, private, static. For more details please dig the Inner Class in java.
Question-Can we declare abstract methods as synchronized?
Yes we can declare the abstract method as synchronized but it would be useless to do so since synchronization is an aspect of the implementation, not the declaration, and abstract methods do not have an implementation. You can use the 'synchronized' modifier on a concrete implementation of an abstract method, which is where it belongs.
Question-Can abstract method declaration include throws clause?
Yes. We can define an abstract class with throws clause.
Question-What are the valid and invalid keywords or modifier with abstract class?
Valid - public, protected and default.
Invalid - static, final and private.
Sunday, 22 May 2016
Abstract Class vs Interface in Java
This is very frequent question asked in Interview.Today we will try to understand the Abstract class and Interface in Java.
1-If need to share code among closely related classes.
interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces.
Abstract Class vs Interface in Java
Abstract Class:-
- A class that is preceded with keyword “abstract” is known as abstract class.
- It extended by other class and its method implemented.
- It can’t be instantiated means we cant create the object of abstract class.
- it may or may not include abstract methods.
- An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), as below,
- If a class contain abstract methods, then the class itself must be declared abstract.
- When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.
- abstract class may contain non-final and final variables.
1-If need to share code among closely related classes.
2-classes that extend your abstract class have many common methods or fields, or require access modifiers other than public.
3-declare non-static or non-final fields. It enables us to define methods that can access and modify the state of the object to which they belong.
Interface :-
- An interface is basically a contract -- it doesn't have any implementation.
- An interface can contain only method declaration; it cannot contain method definition.
- In interface all fields are automatically public, static, and final and all methods (as default methods) are public.
- The class that implements the interface should implement all the members of an interface. Like abstract classes, an interface cannot be instantiated.
- interface is used to "implements“ whereas abstract class is used to "extends".
- interface can be used to achieve multiple inheritance.
interface can be use in below situation,
1-we expect that unrelated classes will implement interface(the interfaces Comparable and Cloneable are implemented by many unrelated classes)
2-Need to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
3-Need to take advantage of multiple inheritance.
Thursday, 7 November 2013
Java Interview Question Part-3
Q- Difference Between Serialization and Externalizable interface?
Serialization is Marker interface which doesnt contains any method.The implemented class just gives the instruction to JVM to behave differently for the implemented class.the main goal of serilaliztaion is persist the state of an object into a stream.
By implementing java.io.Serializable, you get "automatic" serialization capability for objects of your class. No need to implement any other logic, it'll just work. The Java runtime will use reflection to figure out how to marshal and unmarshal your objects.
Q- Write a program in java to find the lenghth of string without using any length or size|().
int findStringLength(String str)
{
char[] elements = str.toCharArray();
int count=0;
for(char c : elements){
count++;
}
return count;
}
Q.what is generic Eraser in java?
When we implement the generic then compiler does these things
1. Type casting if necessary to preserve type safety.
2. Resolve all the cases at compile time. Make safe to run.
3. Generate a bridge to gain polymorphism.
And after this compiler removes the generic type and at runtime it is executed without specific type.
It means bytecode of List
As per the oracle docs,
Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to:
Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
Insert type casts if necessary to preserve type safety.
Generate bridge methods to preserve polymorphism in extended generic types.
Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.
Q.If new object is created by thread then where object's attributes are going to be created? stack or heap?
String str;
MyObject object;
public void m1(){
str = new String("hello");
object = new MyObject();
int i = 10;
}
Suppose now thread A creates object of this class and calls method() then where data, object and i will be created? heap or stack of thread?
Object is allocated in Heap, but reference push to the stack. Also you should know that each thread has his own stack.
All four objects: MyClass, MyObject, String str and "hello" are created in Heap area. In fact there is no way an object can be "created" in stack area. Nevertheless, variable 'i' would be created in the stack of m1().
It does not matter whether "Thread" indirectly creates an object or JVM, objects would always be created in the Heap area only.
Wednesday, 2 October 2013
Java Interview Question Part-2
How can Arraylist be synchronized without using Vector?
Arraylist can be synchronized using:
Collection.synchronizedList(List list)
Other collections can be synchronized:
Collection.synchronizedMap(Map map)
Collection.synchronizedCollection(Collection c)
What is difference between ArrayList and vector?
Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.
Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps?
Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID
Now call Collections.sort() method and pass list as an argument.
How about when Employee class is a jar file and you do not have access to its source code?
Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method .
Call Collections.sort() on the list and pass Comparator as an argument.
What is difference between HashMap and HashTable?
Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are
HashMap is not synchronized in nature but HashTable is.
Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. Fail-safe - if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException
HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null.
What are the prominent implementation of List interface?
The classes that implement List interface:
ArrayList: It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.
Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.
LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.
Which all classes implement Set interface?
SortedSet - It is an interface which extends Set. A the name suggest , the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.
TreeSet - It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.
HashSet: 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 is difference between List and a Set?
List can contain duplicate values but Set doesnt allow. Set allows only to unique elements.
List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.(Except HashSet)
What is difference between Arrays and ArrayList ?
Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as:
int [] intArray= new int[6];
intArray[7] // will give ArraysOutOfBoundException.
Also the size of array cannot be incremented or decremented. But with ArrayList the size is variable. Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime.
List list = new ArrayList();
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.
ArrayList is one dimensional but array can be multidimensional.
int[][][] intArray= new int[3][2][1]; // 3 dimensional array
To create an array the size should be known or initialized to some value. If not initialized carefully there could me memory wastage. But arrayList is all about dynamic creation and there is no wastage of memory.
When to use ArrayList or LinkedList ?
Adding new elements is pretty fast for either type of list. For the ArrayList, doing random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot of editing in the middle of the list.
Consider a scenario. If an ArrayList has to be iterated to read data only, what are the possible ways and which is the fastest?
It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed directly as per the index.
Now another question with respect to above question is if accessing through iterator is slow then why do we need it and when to use it.
For loop does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections have iterator.
Which design pattern Iterator follows?
It follows Iterator design pattern. Iterator Pattern is a type of behavioral pattern. The Iterator pattern is one, which allows you to navigate through a collection of data using a common interface without knowing about the underlying implementation. Iterator should be implemented as an interface. This allows the user to implement it anyway its easier for him/her to return data. The benefits of Iterator are about their strength to provide a common interface for iterating through collections without bothering about underlying implementation.
Example of Iteration design pattern - Enumeration The class java.util.Enumeration is an example of the Iterator pattern. It represents and abstract means of iterating over a collection of elements in some sequential order without the client having to know the representation of the collection being iterated over. It can be used to provide a uniform interface for traversing collections of all kinds.
Is it better to have a HashMap with large number of records or n number of small hashMaps?
It depends on the different scenario one is working on:
If the objects in the hashMap are same then there is no point in having different hashmap as the traverse time in a hashmap is invariant to the size of the Map.
If the objects are of different type like one of Person class , other of Animal class etc then also one can have single hashmap but different hashmap would score over it as it would have better readability.
Why is it preferred to declare: List list = new ArrayList(); instead of ArrayList = new ArrayList();
It is preferred because
If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that.
The most important one – If a function is declared such that it takes list. E.g void showDetails(List list);
When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible.
What is difference between iterator access and index access?
Index based access allow access of the element directly on the basis of index. The cursor of the data structure can directly goto the 'n' location and get the element. It does not traverse through n-1 elements.
In Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the 'n'th element it need to traverse through n-1 elements.
Insertion,updation or deletion will be faster for iterator based access if the operations are performed on elements present in between the datastructure.
Insertion,updation or deletion will be faster for index based access if the operations are performed on elements present at last of the datastructure.
Traversal or search in index based datastructure is faster.
ArrayList is index access and LinkedList is iterator access.
Can a null element added to a Treeset or HashSet?
A null element can be added only if the TreeSet contains one element because when a second element is added then as per set definition a check is made to check duplicate value and comparison with null element will throw NullPointerException. HashSet is based on hashMap and can contain null element.
How to sort list of strings - case insensitive?
using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
What is ConcurrentHashMap?
A concurrentHashMap is thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtable in terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance.
What is identityHashMap?
The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.
What is WeakHashMap?
A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations
Any Comment and suggestion must be appreciated :-)
Arraylist can be synchronized using:
Collection.synchronizedList(List list)
Other collections can be synchronized:
Collection.synchronizedMap(Map map)
Collection.synchronizedCollection(Collection c)
What is difference between ArrayList and vector?
Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.
Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps?
Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID
Now call Collections.sort() method and pass list as an argument.
How about when Employee class is a jar file and you do not have access to its source code?
Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method .
Call Collections.sort() on the list and pass Comparator as an argument.
What is difference between HashMap and HashTable?
Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are
HashMap is not synchronized in nature but HashTable is.
Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. Fail-safe - if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException
HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null.
What are the prominent implementation of List interface?
The classes that implement List interface:
ArrayList: It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.
Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.
LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.
Which all classes implement Set interface?
SortedSet - It is an interface which extends Set. A the name suggest , the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.
TreeSet - It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.
HashSet: 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 is difference between List and a Set?
List can contain duplicate values but Set doesnt allow. Set allows only to unique elements.
List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.(Except HashSet)
What is difference between Arrays and ArrayList ?
Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as:
int [] intArray= new int[6];
intArray[7] // will give ArraysOutOfBoundException.
Also the size of array cannot be incremented or decremented. But with ArrayList the size is variable. Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime.
List list = new ArrayList();
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.
ArrayList is one dimensional but array can be multidimensional.
int[][][] intArray= new int[3][2][1]; // 3 dimensional array
To create an array the size should be known or initialized to some value. If not initialized carefully there could me memory wastage. But arrayList is all about dynamic creation and there is no wastage of memory.
When to use ArrayList or LinkedList ?
Adding new elements is pretty fast for either type of list. For the ArrayList, doing random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot of editing in the middle of the list.
Consider a scenario. If an ArrayList has to be iterated to read data only, what are the possible ways and which is the fastest?
It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed directly as per the index.
Now another question with respect to above question is if accessing through iterator is slow then why do we need it and when to use it.
For loop does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections have iterator.
Which design pattern Iterator follows?
It follows Iterator design pattern. Iterator Pattern is a type of behavioral pattern. The Iterator pattern is one, which allows you to navigate through a collection of data using a common interface without knowing about the underlying implementation. Iterator should be implemented as an interface. This allows the user to implement it anyway its easier for him/her to return data. The benefits of Iterator are about their strength to provide a common interface for iterating through collections without bothering about underlying implementation.
Example of Iteration design pattern - Enumeration The class java.util.Enumeration is an example of the Iterator pattern. It represents and abstract means of iterating over a collection of elements in some sequential order without the client having to know the representation of the collection being iterated over. It can be used to provide a uniform interface for traversing collections of all kinds.
Is it better to have a HashMap with large number of records or n number of small hashMaps?
It depends on the different scenario one is working on:
If the objects in the hashMap are same then there is no point in having different hashmap as the traverse time in a hashmap is invariant to the size of the Map.
If the objects are of different type like one of Person class , other of Animal class etc then also one can have single hashmap but different hashmap would score over it as it would have better readability.
Why is it preferred to declare: List
It is preferred because
If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that.
The most important one – If a function is declared such that it takes list. E.g void showDetails(List list);
When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible.
What is difference between iterator access and index access?
Index based access allow access of the element directly on the basis of index. The cursor of the data structure can directly goto the 'n' location and get the element. It does not traverse through n-1 elements.
In Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the 'n'th element it need to traverse through n-1 elements.
Insertion,updation or deletion will be faster for iterator based access if the operations are performed on elements present in between the datastructure.
Insertion,updation or deletion will be faster for index based access if the operations are performed on elements present at last of the datastructure.
Traversal or search in index based datastructure is faster.
ArrayList is index access and LinkedList is iterator access.
Can a null element added to a Treeset or HashSet?
A null element can be added only if the TreeSet contains one element because when a second element is added then as per set definition a check is made to check duplicate value and comparison with null element will throw NullPointerException. HashSet is based on hashMap and can contain null element.
How to sort list of strings - case insensitive?
using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
What is ConcurrentHashMap?
A concurrentHashMap is thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtable in terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance.
What is identityHashMap?
The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.
What is WeakHashMap?
A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations
Any Comment and suggestion must be appreciated :-)
Subscribe to:
Posts (Atom)
Find Duplicate Characters In String using Java
package com.zia.test; import java.util.HashMap; import java.util.Map; import java.util.Set; public class findDuplicateCharacter { /**...
-
public class Program { public static int getClosestToZero(int[] a) { /* Please implement this method to return the number in...
-
public class FizzBuzzProgramme { public static void main(String[] args) { boolean flag; for (int i = 1; i