Friday, 31 May 2013

Collections Example in JAVA

Please see the comments in below example to understand differences between hashset and treeset as well as hashmap and treemap. Just run this example ,you will get the differences easily.
================================================
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;

public class CollectionExample {

@SuppressWarnings("unchecked")
public static void main(String a[]) {

// =============================================
/**
 * List allows Duplicate values
 */
List list = new ArrayList();
list.add("krishna");
list.add("krishna1");
list.add("krishna1");
list.add("krishna");
list.add(new String("anusha"));
list.add(new String("anusha"));
list.add(new Integer(8));
System.out.println(list.toArray().length);
;
System.out.println(list);

// =============================================

/**
 * Vector allows Duplicate values. It is legacy class(Synchronised)
 */
Vector vector = new Vector();
vector.addElement("krishna");
vector.addElement("krishna1");
vector.addElement("krishna11");
vector.addElement("krishna");
vector.addElement(new String("anusha"));
vector.addElement(new String("anusha"));
vector.addElement(new Integer(8));
Enumeration enumeration = vector.elements();
while (enumeration.hasMoreElements()) {
System.out.println(enumeration.nextElement());

}

// ==============================================

/**
 * if key is different and content is same for three values then it will
 * print all values as shown below example HashMap allows null as key
 * values(Using EntrySet Method)
 */

Map map = new HashMap();
map.put("one", "krishna");
map.put("one1", "krishna");
map.put("two", "munna");
map.put("three", "balu");
map.put("four", "tiger");
map.put(null, null);
map.put(null, null);
map.put(null, "null key3");
Set set = map.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry object = (Map.Entry) iterator.next();
System.out.println(object.getKey() + "*******" + object.getValue());

}

// ==============================================

/**
 * if key is different and content is same for three values then it will
 * print all values as shown below example HashMap allows null as key
 * values(Using KeySet Method)
 */

Map map2 = new HashMap();
map2.put("one", "krishna");
map2.put("one1", "krishna");
map2.put("two", "munna");
map2.put("three", "balu");
map2.put("four", "tiger");
map2.put(null, null);
map2.put(null, null);
map2.put(null, "null key3");
Set set2 = map2.keySet();
Iterator iterator2 = set2.iterator();
while (iterator2.hasNext()) {
Object object = (Object) iterator2.next();
System.out.println(object + "***#############****"
+ map2.get(object));

}

// =============================================
/**
 * if key is different and content is same for three values then it will
 * print all values as shown below example. HashMap allows null as key
 * values(Using KeySet Method).Hash Map supports different types of
 * objects like strings,integers as values and as well as keys.
 */

Map map42 = new HashMap();
map42.put("one", "krishna");
map42.put("one1", "krishna");
map42.put("two", "munna");
map42.put("three", "balu");
map42.put("four", "tiger");
map42.put(null, null);
map42.put(null, null);
map42.put(null, "null key3");
map42.put(new Integer(54), "null key3");// /integer as key
map42.put("integer", new Integer(88));// integer as value
Set set42 = map42.keySet();
Iterator iterator42 = set42.iterator();
while (iterator42.hasNext()) {
Object object = (Object) iterator42.next();
System.out.println(objec+ "****&&&&&&&&&&&&&&&&"+ map42.get(object));

}

// ==============================================

/**
 * if key is same and content is same for three values then it will
 * print last value like shown below TreeMap may supports null values
 * but key must be not null(using KeySet Method)
 */
Map map1 = new TreeMap();
map1.put("one", "krishna");
map1.put("one", "krishna1");
map1.put("two", "munna");
map1.put("three", "balu");
// map1.put(null, "anusha");
map1.put("four", "tiger");
Set set1 = map1.keySet();
Iterator iterator1 = set1.iterator();
while (iterator1.hasNext()) {
String object = (String) iterator1.next();
System.out.println(map1.get(object));

}

//==============================================

/**
 * if key is same and content is same for three values then it will
 * print last value like shown below TreeMap may supports null values
 * but key must be not null(Using EntrySet Method)
 */
Map map11 = new TreeMap();
map11.put("one", "krishna");
map11.put("one", "krishna1");
map11.put("two", "munna");
map11.put("three", "balu");
map11.put("four", "tiger");
Set set11 = map11.entrySet();
Iterator iterator11 = set11.iterator();
while (iterator11.hasNext()) {
Map.Entry object = (Map.Entry) iterator11.next();
System.out.println(object.getKey() + "}}}}}}}}}}}}}}}"
+ object.getValue());

}

// ==============================================
/**
 * if key is same and content is same for three values then it will
 * print last value like shown below TreeMap may supports null values
 * but key must be not null(Using EntrySet Method). Tree Map supports
 * different types of objects like strings,integers but key must be same
 * other wise exception will raise java.lang.ClassCastException:
 * java.lang.String cannot be cast to java.lang.Integer.
 */
Map map111 = new TreeMap();
map111.put("one", "krishna");
map111.put("one", "krishna1");
map111.put("two", "munna");
map111.put("three", "balu");
map111.put("four", new Integer(9));// integer as value
// map111.put(new Integer(88), new Integer(99));//integer as key not
// support in Tree Map
Set set1411 = map111.entrySet();
Iterator iterator4111 = set1411.iterator();
while (iterator4111.hasNext()) {
Map.Entry object = (Map.Entry) iterator4111.next();
System.out.println(object.getKey()+ "}}}}}}************}}}"+ object.getValue());

}

// ===============================================

/**
 * Tree set supports same types of objects. If we add String it will
 * throw exception java.lang.Integer cannot be cast to java.lang.String
 * Set support duplicate values while adding but it does not iterate
 * through duplicates.
 */

TreeSet set111 = new TreeSet();
set111.add(new Integer(1111));
set111.add(new Integer(155551));
set111.add(new Integer(111));
set111.add(new Integer(1111));// Duplicate value
// set111.add("krishna");
Iterator iterator22 = set111.iterator();
while (iterator22.hasNext()) {
System.out.println("%%%%%%%@@@@@@"+ iterator22.next());

}

// ==============================================

/**
 * Set does not allow duplicates but if we are trying to add it will
 * supports but it can not iterate through duplicates and also it check
 * the address not the content for duplication. In below example content
 * is same but are adding three different instances of class
 *
 */
Set set1111 = new HashSet();
  // We have BeanExample implementation below of this class.
BeanExample beanExample = new BeanExample();
beanExample.setUserName("krishna");
beanExample.setPassword("krishna");
set1111.add(beanExample);
BeanExample beanExample1 = new BeanExample();
beanExample1.setUserName("krishna");
beanExample1.setPassword("krishna");
set1111.add(beanExample1);
BeanExample beanExample11 = new BeanExample();
beanExample11.setUserName("krishna");
beanExample11.setPassword("krishna");
set1111.add(beanExample11);

System.out.println("@@@@@@@@@@@@@@@@@@@" + set1111.size());
Iterator iterator111 = set1111.iterator();
while (iterator111.hasNext()) {
// System.out.println(iterator.next());
BeanExample beanExample2 = (BeanExample) iterator111.next();
String userName = beanExample2.getUserName();
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$" + userName);
}

// ==============================================

/**
 * Tree set will iterate the values in ascending order. Tree set does
 * not supports different types of objects.
 */
Set set22 = new TreeSet();
set22.add("munna");
set22.add("krishna");
set22.add("anusha");
set22.add("kusuma");
Iterator iterator21 = set22.iterator();
while (iterator21.hasNext()) {
System.out.println(iterator21.next());
}

// ==============================================

/**
 * Hash set supports different types of objects. Set support duplicate
 * values while adding but it does not iterate through duplicates.
 */
HashSet stringSet = new HashSet();
String string = "krishna";
Integer integer = new Integer(8);
stringSet.add(integer);
stringSet.add(integer);
stringSet.add(new Integer(9));
System.out.println("###########################" + stringSet.size());
Iterator iterator1111 = stringSet.iterator();

while (iterator1111.hasNext()) {
System.out.println("%%%%%%%%%%%%%%%%%%%%" + iterator1111.next());
}
stringSet.add(string);
stringSet.add(string);
Iterator stringIterator = stringSet.iterator();
while (stringIterator.hasNext()) {
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
+ stringIterator.next());
}

// ==============================================
/**
 * Filtering the list based on data
 */
List<String> stringsList = new ArrayList<String>();
stringsList.add("BalaKrishna");
stringsList.add("Krishna");
stringsList.add("anusha");
stringsList.add("BalaKrishna");
stringsList.add("Krishna");
stringsList.add("anusha");
Iterator<String> stringIerator = stringsList.iterator();
String previousString = null;
String presentString = null;
String matchedString = null;
while (stringIerator.hasNext()) {
previousString = (String) stringIerator.next();
presentString = (String) stringIerator.next();
if (previousString.equalsIgnoreCase(presentString)) {
matchedString = presentString;
}
System.out.println("++++++++++++++++++++++++++++++"+matchedString);

}
// ==============================================
}
}


In order to run this(above) class we have to write below class(Dependency see colour).

//=================================================

package com.sample.java.testing;

public class BeanExample {

private String userName = null;
private String password = null;

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

}
//======================================================

Collections in JAVA

The Java Collections Framework provide Java developers with a set of classes and interfaces that makes it easier to handle collections of objects. In a sense Collection's works a bit like arrays, except their size can change dynamically, and they have more advanced behaviour than arrays.

A collection is simply an object that groups multiple elements into a single unit. It is also called as a container sometimes.

What Is a Collections Framework?

A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:
  • Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation.
  • Implementations(i.e, Classes): These are the concrete implementations of the collection interfaces.
  • Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality.
Benefits of the Java Collections Framework:

Reduces programming effort: By providing useful data structures and algorithms, the Collections Framework frees you to concentrate on the important parts of your program rather than on the low-level "plumbing" required to make it work.

Increases program speed and quality: This Collections Framework provides high-performance, high-quality implementations of useful data structures and algorithms. The various implementations of each interface are interchangeable, so programs can be easily tuned by switching collection implementations. Because you're freed from the drudgery of writing your own data structures, you'll have more time to devote to improving programs' quality and performance.

Allows interoperability among unrelated APIs: The collection interfaces are the vernacular by which APIs pass collections back and forth. 

Reduces effort to learn and to use new APIs: Many APIs naturally take collections on input and furnish them as output. In the past, each such API had a small sub-API devoted to manipulating its collections. There was little consistency among these ad hoc collections sub-APIs, so you had to learn each one from scratch, and it was easy to make mistakes when using them. With the advent of standard collection interfaces, the problem went away.

Reduces effort to design new APIs: This is the flip side of the previous advantage. Designers and implementers don't have to reinvent the wheel each time they create an API that relies on collections; instead, they can use standard collection interfaces.

Fosters software reuse: New data structures that conform to the standard collection interfaces are by nature reusable. The same goes for new algorithms that operate on objects that implement these interfaces.

Packages in JAVA

Definition: A package is a grouping of related types providing access protection and name space management. Note that types refers to classes, interfaces, enumerations, and annotation types. Packages helps Organize your classes into a folder structure and make it easy to locate and use them. More importantly, packages helps improve re-usability.
Syntax:- package <package_name>;
*******************************************************
Example1: To create a package

Step 1: Copy the following code into an editor
package p1;
class c1{

public void m1(){
System.out.println("Method m1 of Class c1");
}

public static void main(String args[]){
c1 obj = new c1();
obj.m1();
}
}
Step 2: Save the file as Demo.java.
Step 3:  Compile the file as, javac – d . Demo.java
Step 4: Run the code as java p1.c1
*******************************************************
Example2: To create a sub-package
Step1:  Copy the following code into an editor
package p1.p2;
class c2{
public void m2(){
System.out.println("Method m2 of Class c2");
}
public static void main(String args[]){
c2 obj = new c2();
obj.m2();
}

}
Step 2:  Save the file as Demo2.java.
Step 3:  Compile the file as javac – d . Demo2.java
Step 4:  Run the code as java p1.p2.c2
*******************************************************

The "import" Keyword:
If a class wants to use another class in the same package, the package name does not need to be used. Classes in the same package find each other without any special syntax.

Example:
Here a class named Manager is added to the payroll package that already contains Employee. The Manager can then refer to the Employee class without using the payroll prefix, as demonstrated by the following Manager class.

package payroll;

public class Manager
{
   public void payEmployee(Employee e)
   {
      e.mailCheck();
   }
}

What happens if Manager is not in the payroll package?
The Manager class must then use one of the following techniques for referring to a class in a different package.

The fully qualified name of the class can be used. For example:

payroll.Employee

The package can be imported using the import keyword and the wild card (*).

For Example: import payroll.*;

The class itself can be imported using the import keyword.

For Example: import payroll.Employee;

Note: A class file can contain any number of import statements. The import statements must appear after the package statement and before the class declaration.

Following is the example to show how do we access the class that is not existing in same package using import keyword.
**********************************************
Step:1
package com.sample.java.testing;

public class PackageExample1 {

public String getName() {
System.out.println("getName of PackageExample1");
return "PackageExample1 method";
}

public static void main(String s[]) {
PackageExample1 example1 = new PackageExample1();
example1.getName();
}
}

Step 2: Save the file as PackageExample1 .java.
Step 3: Compile the file as, javac – d . PackageExample1.java. 
Then it will create class file under folders 
com/sample/java/testing/PackageExample1.class if no compile time errors.
Step 4: Run the code as java com.sample.java.testing.PackageExample1

*****************************************

package com.sample.javase.testing;
//need to write this import statement if you want to use a class not exist in the same package
import com.sample.java.testing.PackageExample1;

public class PackageExample2 {

public void getName(PackageExample1 example1) {
System.out.println("getName of PackageExample2" + example1.getName());
}

public static void main(String s[]) {
PackageExample1 example1 = new PackageExample1();
PackageExample2 example2 = new PackageExample2();
example2.getName(example1);
}
}


********************************

Multiple Inheritance in JAVA

Multiple Inheritance:
Multiple inheritance is where we inherit the properties and behavior of multiple classes to a single class.


Why Java does not support multiple inheritance?

Now we are sure that there is no support for multiple inheritance in java. But why?

JAVA: A simple, object oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high performance, multithreaded, dynamic language.

Look at the beauty of this definition for java. This should be the definition for a modern software language. What is the first characteristic in the language definition? It is simple.

In order to enforce simplicity should be the main reason for omitting multiple inheritance. For instance, we can consider below problem of multiple inheritance.



We have two classes B and C inheriting from A. Assume that B and C are overriding an inherited method and they provide their own implementation. Now D inherits from both B and C doing multiple inheritance. D should inherit that overridden method, which overridden method will be used? Will it be from B or C? Here we have an ambiguity.

Where as using interfaces we could not get the ambiguity problem. See the below.

A class can implement multiple interfaces. In that case the class must implement all the methods declared in all the interfaces implemented. 

Multiple inheritance is not supported in case of classes but it is supported in case of interfaces because there is no ambiguity in as implementation of method is provided by implementation class.

Here is an example:

********************************************************

public interface FourWheeler {

public void getPrice();
        public void getCompany();
}

=======================================

public interface TwoWheeler {

public void getWheels();
        public void getCompany();
}

=======================================

/**
 * Here Class implements the multiple interfaces. Here we have getCompany()
 * method in both the interfaces and we are implementing both the interfcaes.
 * but we did not get any ambiguity because method implementation is 
 * provided by class.So there is no ambiguity in interfaces. So multiple 
 * inheritance is supported by interfaces.
 */
public class Vehicle implements TwoWheelerFourWheeler {

/**
 * @param args
 */
public static void main(String[] args) {
/**
 * Here we are creaintg the instace of an class and assign it to
 * reference of an class.SO we ca naceess the bothe the methods 
   * in 2 interfaces.
 */
     Vehicle vehicle = new Vehicle();
     vehicle.getWheels();
           vehicle.getPrice();
     vehicle.getCompany();
/**
 * Here we are creating instance of class but assign it to reference 
   * of TwoWheeler interfcae. So we can not access the method of 
   * FourWheeler interface method. so comment the line of code.
 */
    TwoWheeler twoWheeler = new Vehicle();
    twoWheeler.getWheels();
    twoWheeler.getCompany();
    // twoWheeler.getPrice();
/**
 * Here we are creating instance of class but assgn it to reference 
   * of FourWheeler interfcae. So we can not access the method of 
   * TwoWheeler interface method. so commentd the line of code.
 */
    FourWheeler fourWheeler = new Vehicle();
    fourWheeler.getPrice();
    twoWheeler.getCompany();
    // fourWheeler.getWheels();
}

@Override
public void getPrice() {
System.out.println("get 4 whellers price");
}

@Override
public void getWheels() {
System.out.println("get 2 wheelers models");
}

@Override
public void getCompany() {
System.out.println("get company of vehicles");
}
  }

********************************************************
So, remember that although Java does not have multiple inheritance, a Java class does have the ability to implement multiple interfaces instead.

Interfaces in JAVA

A Java interface is a bit like a class, except you can only declare methods and variables in the interface. You cannot actually implement the methods.

Syntax for declaring interface:

public interface interfacename{
//variable declaration here
//methods declaration here
public int 1 =10;
public void methodnmae();
}

As you can see, an interface is declared using the Java keyword "interface".

The interface contains variables and methods. 

The variable can be accessed directly from the interface, like 

System.out.println(interfacename.i);

The method, however, needs to be implemented by some class, before you can access it. 

To use a interface in your class, append the keyword “implements” after your class name followed by the interface name

Example: class Car implements Vehicle

Implementing an Interface:

Before you can really use an interface, you must implement that interface in some class. Here is a class that implements the MyInterface interface:

*********************************************************

Interface definition:

public interface MyInterface {

    public String h = "Hello";

    public void sayHello();
}

**********************************************************

Class definition:

public class MyInterfaceImpl implements MyInterface {

    public void sayHello() {
        System.out.println(MyInterface.hello);
    }
}

**********************************************************

Notice the "implements MyInterface" part of the above class declaration. This signals to the Java compiler that the MyInterfaceImpl class implements the MyInterface interface.

A class that implements an interface must implement all the methods declared in the interface. The methods must have the exact same signature (name + parameters) as declared in the interface. The class does not need to implement (declare) the variables of an interface. Only the methods.

Rules for Interfaces:
  • The class which implements the interface needs to provide functionality for the methods declared in the interface
  • All methods in an interface are implicitly public and abstract
  • Variables in interfaces are static and final by default in Java
  • An interface cannot be instantiated
  • An interface reference can point to objects of its implementing classes
  • An interface can extend from one or many interfaces. A class can extend only one class but implement any number of interfaces
Java compiler converts methods of interface as public and abstract, datamembers as public, final and static by default.





Interface Instances:  we can not create instance for interfaces. Instead we can follow the below steps.

Once a class implements an interface you can use an instance of that class as an reference of that interface. Here is an example:

MyInterface myInterface = new MyInterfaceImpl();
myInterface.sayHello();

Notice how the variable is declared to be of the interface type MyInterface while the object created is of type MyInterfaceImpl. This is possible because the class MyInterfaceImpl implements the MyInterface interface. You can then reference instances of the MyInterfaceImpl class as instances of the MyInterface interface.

You cannot create instances of an interface by itself. You must always create an instance of some class that implements the interface, and reference that instance as an instance of the interface.

Example:

************************************************

public interface InterfaceSample {

/**
 * We can not create the instance for an interface. So class must 
  * implement the interface to give implementation for the method.
 */
public void getName();
 int i = 10;
}

==================================

public class InterFaceDemo implements InterfaceSample {

// Interface method
public void getName() {
System.out.println("getName of class");
}

// class own method
public void getName1() {
System.out.println("getName1 of class");
}

public static void main(String[] a) {

/**
 * Following line creates object of class InterfaceDemo. So we can 
   * access all methods of class using this object.
 */
      InterFaceDemo demo = new InterFaceDemo();
      demo.getName1();
       demo.getName();

/**
 * As we could not create instance for an interface we can assign 
   * the object of class which implements the interface to reference 
   * of an interface as shown below. Following line creates the 
   * object of class but assigns it to reference of an interface. So 
   * here using this reference we can not access the method 
   * getName1(as it is class's own method not interface's method). 
   * So i commented the line of code.But we are able to access 
   * getName() method as it is interface's method.
 */
// It assigns the instance of class to reference of an interface. 
  // JUST FYI: This is way to achieve polymorphism. But here do not   
  // concentrate on polymorphism. Understand the assigning  instance of 
  // class to reference of an interface.
      InterfaceSample interfaceSample = new InterFaceDemo();
      interfaceSample.getName();
        // interfaceSample.getName1()
        System.out.println(InterfaceSample.i);   
   }
}

************************************************
Note:-1: A class can implements interface and one interface can extends the another interface.

Example:

***************************************************

public interface CarInterface {
public void getModel();
}

====================================

public interface BikeInterface extends CarInterface {
public void getBikeModel();
}

=====================================

/**
 * Here class implements BikeInterface where as BikeInterface extends 
 * CarInterfcae. So here we need to provide implementation for both the 
 * the methods in interfaces.                                                                              
 */

public class ImplementClass implements BikeInterface {

@Override
public void getModel() {
System.out.println("get car model");
}

@Override
public void getBikeModel() {
System.out.println("get bike model");
}

public static void main(String a[]) {

ImplementClass class1 = new ImplementClass();
class1.getBikeModel();
class1.getModel();

CarInterface carInterface = new ImplementClass();
carInterface.getModel();

BikeInterface bikeInterface = new ImplementClass();
bikeInterface.getBikeModel();

/**
 * getmodel1() is method of CarInterface but here we can acess
 * this using BikeInterface reference because BikeInterfcae extends the
 * CarInterface
 */
bikeInterface.getModel();
}
}

***************************************************

What is marker or tagged interface?
An interface that have no member is known as marker/tagged interface.

Example: Serializable is marker interface.

public interface Serializable {
}

Uses: Marker interfaces are used to provide some essential information to the JVM so that JVM may perform some useful operation.