Thursday, 13 December 2012

Iterate through HashMap


Iterate through the entrySet like so:

public static void printMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
        it.remove(); // avoids a ConcurrentModificationException
    }
}


If you're only interested in the keys, you can iterate through the keySet() of the map:

Map<String, Object> map = ...;
for (String key : map.keySet()) {
    // ...
}

If you only need the values, use values():
for (Object value : map.values()) {
    // ...
}

Finally, if you want both the key and value, use entrySet():
for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}

Source;- stackoverflow

Example Code:-

MapIteration.java
package collection.iteration;

import java.util.*;
import java.util.Map.Entry;

public class MapIteration {

public static void main(String[] args) {
Map <String,Employee> map= new HashMap<String,Employee>();
Employee emp1= new Employee(25, "Hitesh");
Employee emp2= new Employee(26, "Rajan");
Employee emp3= new Employee(27, "Dinesh");
Employee emp4= new Employee(24, "Neha");

map.put("e1",emp1);
map.put("e2",emp2);
map.put("e3",emp3);
map.put("e4",emp4);
System.out.println(map.keySet()); // Displaying all keys
System.out.println(map.values()); // Displaying all values
for(Map.Entry<String, Employee> entry : map.entrySet()){
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}

}
And
 Employee.java


package collection.iteration;

public class Employee implements Comparable<Employee> {
int age;
String name;

Employee(int age, String name){
this.age=age;
this.name=name;
}
Employee(){

}
public String toString(){
return("The age is "+age+" and the name is "+name);
}

public int compareTo(Employee e){
return name.compareTo(e.name);
}
}


 Output:

[e3, e4, e1, e2]
[The age is 27 and the name is Dinesh, The age is 24 and the name is Neha, The age is 25 and the name is Hitesh, The age is 26 and the name is Rajan]
e3
The age is 27 and the name is Dinesh
e4
The age is 24 and the name is Neha
e1
The age is 25 and the name is Hitesh
e2
The age is 26 and the name is Rajan




Regards
Rajan Bansal

When hashSet and equals methods executes

class Person
{
    String name;

    Person(String n)
    {
        name=n; 
    }
    public String getName()
    {
        return name;   
    }

    @Override
    public boolean equals(Object arg0) {

        System.out.println("in equals");

        Person obj=(Person)arg0;

        System.out.println("1st "+getName());
        System.out.println("2nd "+obj.getName());

        if(this.getName().equals(obj.getName()))
        {
                return true;
        }
        return false;
    }


    @Override
    public int hashCode() {

        System.out.println("in hash code");
        System.out.println(" value is "+Integer.valueOf(name.charAt(0)));
        return Integer.valueOf(name.charAt(0));
    }
}

In main I have the following code

Person obj1=new Person("bcd");

Person obj2=new Person("cde");

Person obj3=new Person("abc");

Person obj4=new Person("abc");

Now if I add these objects to hashset

Set<Person> sset=new HashSet<Person>();

sset.add(obj1);
sset.add(obj4);
sset.add(obj2);
sset.add(obj3);

I am getting this output

in hash code                                                                      
value is 98    
in hash code   
value is 97    
in hash code    
value is 99    
in hash code    
value is 97  
in equals  
1st abc     
2nd abc

Question 1 : why equals() function is called only once for checking obj3 and obj4 ? Why its not checked for rest of the objects ?

Question 2 : If the answer is because they both have same hash code,only then equals will be called, then why its not called for below code

sset.add(obj1);
sset.add(obj4);
sset.add(obj2);
sset.add(obj4);
output is :

in hash code  
value is 98  
in hash code   
value is 97   
in hash code   
value is 99   
in hash code  
value is 97 
It's not going inside equals() method even though two same objects are added to hash set which has same hash code.

Question 4 :I iterated the above value and printed the contents but neither hashcode nor equals were called. when its really useful to override hashcode and equals method ?

Question 3 : when hash code and equals will be called ?


Answers:

1.There's no need to call equals if hashCode differs
2.There's no need to call hashCode if (obj1 == obj2)
3.There's no need for hashCode and/or equals just to iterate - you're not comparing objects
4. When needed to distinguish in between objects.


Source: stackoverflow

Regards
Rajan Bansal

Tuesday, 11 December 2012

What is MVC framework using Spring


The MVC is a standard software architecture that aims to separate business logic from presentation logic, enabling the development, testing and maintenance of both isolated .

The picture below depicts the flow of information in the MVC pattern :


(1) The user triggers an event through the UI (click a button on the page or something).
(2) The controller receives the event and coordinates how things will happen on the server side, i.e. the flow goes to the objects required to perform the business rule.
(3) The model is used to represent the business information so it is called by the controller to perform the business rule that should be done. The model can also be used to send data to the view layer.
(4) After the controller performs business rule using the model it renders a new view and sends it to the user. Create an application using the MVC pattern is nothing more than to separate the logic in “packages” and make that information follow a certain path.

Information flow diagram of Spring Web MVC :


(1) A request from the user always arrives in a single servlet Dispatcher Servlet. This is a very common pattern in MVC frameworks called front controller (front controller) where a single servlet is responsible for receiving the request, delegate processing to other components of the application and return a response to the user.
(2) Once the Dispatcher servlet gets the request it must find out which controller the request will be sent. So it asks for help in the Handler Mapping. Based on the request URL Handler Mapping finds the controller.
(3) The request is then sent to the controller that will take care of the data contained therein. Once the controller receives the request it processes the data and performs some business rules of the application.
(4) Often rendered by the logic controller results in some information that should be taken back to the user (the model). Only sending information back is not enough, it must be formatted in a way that the user can understand, for that controller send it to the view. For this model and the view are encapsulated in a ModelAndView object and returned to the Dispatcher.
(5) As the controller is not stuck to just one view it sends a hint in the ModelAndView object to the Dispatcher to know which view should send the data. The Dispatcher passes this hint to viewResolver that returns the view which should be called.
(6) Finally, the Dispatcher sends the information (model) to the view (JSP page) who has just discovered. The page renders the information received and is returned to the user.
Here the original version: Original Version


Wednesday, 10 October 2012

what is the difference between declarative and imperative programming

In other words, Non-Procedural (declarative) and Procedural (imperitive):


Declarative programming is where you say what you want without having to say how to do it. For example, SQL is more declarative than procedural, because the queries don't specify steps to produce the result. Eg: SQL, XSLT, HTML etc
 With procedural programming, you have to specify exact steps to get the result. Eg; C, C++, Java, .net and many other.

With imperative programming, you tell the compiler what you want to happen, step by step.
For example, let's start with this collection, and choose the odd numbers:
List<int> collection = new List<int> { 1, 2, 3, 4, 5 };
With imperative programming, we'd step through this, and decide what we want:
List<int> results = new List<int>();
foreach(var num in collection)
{
    if (num % 2 != 0)
          results.Add(num);
}
Here, we're saying:
  1. Create a result collection
  2. Step through each number in the collection
  3. Check the number, if it's odd, add it to the results
With declarative programming, on the other hand, you write code that describes what you want, but not necessarily how to get it (declare your desired results, but not the step-by-step):
var results = collection.Where( num => num % 2 != 0);
Here, we're saying "Give us everything where it's odd", not "Step through the collection. Check this item, if it's odd, add it to a result collection." 


Differences between SQL and PL-SQL

SQL is a query language that allows you to issue a single query or execute a single insert/update/delete.
PL-SQL is Oracle's "Programming Langugage" SQL, which allows you to write a full program (loops, variables, etc.) to accomplish multiple selects/inserts/updates/deletes.

Regards
Rajan Bansal

Saturday, 6 October 2012

What is DELIMITER //


Hi,
It changes the statement delimiter from ; to //. This is so you can write ; in your trigger definition without the MySQL client misinterpreting that as meaning you're done with it.
Note that when changing back, it's DELIMITER ;, not DELIMITER; as I've seen people try to do.
source: stackoverflow.com

Sunday, 26 August 2012

What happen when Class.forName("com.mysql.jdbc.Driver"); executes

Hi,

Several times we saw the code like this:

Class.forName("com.mysql.jdbc.Driver");
  Connection connection = null;
  connection = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","uname", "pass");

When Class.forName(com.mysql.jdbc.Driver") executes
then it will search for the Driver class in package com.mysql.jdbc.
If it finds then  it loads the Driver class and instantiate it,
otherwise it will throw the "ClassNotFoundException".

During instantiation it will execute the static block of that "Driver class" which will register it to the "DriverManager" as under:

static
    {
        try
        {
            DriverManager.registerDriver(new Driver());
        }
        catch(SQLException E)
        {
            throw new RuntimeException("Can't register driver!");
        }
    }

This registration is important because when "connection = DriverManager.getConnection(
          "jdbc:mysql://hostname:port/dbname","username", "password");" executes then it  tries to make the database connection using that Driver.

Eg"- If we try to make the connection to the SQLdatabase and we write the Class.forName("oracle.jdbc.OracleDriver"); then it does not make the connection.
For connection to the SQL DB we must have registered the SQL Driver.
This happens to every database like Oracle, SQL, Microsoft, hsql, derby etc.

And we can create db connections to different database as under:

Class.forName("oracle.jdbc.OracleDriver"); 
Class.forName("com.mysql.jdbc.Driver");
 Connection sqlConnection = null;
 Connection oracleConnection = null;


sqlConnection = DriverManager.getConnection(
          "jdbc:mysql://hostname:port/dbname","username", "password");"


oracleConnection = DriverManager.getConnection(
          "jdbc:oracle://hostname:port/dbname","username", "password");"

In the above code, DriverManager tries to make the connection by using all the drivers registered, if using the first driver the connections is not established, then it tries the next one until the connection is established or the drivers are finished.

Hope this information is helpful.

Regards
Rajan Bansal





Making of executable jar by using "jar" utility in jdk

Hi,

We can make the jars and executable jars by using the  "jar" utility present in the jdk as under:

1. Create the class having the main() method in package say main.pckage.MainClass.java
2. Create another class having any method in package say com.other.pckage.OtherClass.java.
3. Compile both classes.
4. Create a text file say manifest.txt and write the Main-Class: main.pckage.MainClass
5. Now we have two main folder main and com containing the .class files and one manifest.txt file.
6. Put all these in one folder say "Executable Jar".
7. I assume that you set the java path variable.
8. Open the command prompt and paste the
cmd-->  C:\Users\Rajan Bansal\Desktop\Executable Jar>jar cvfm myjar.jar manifest.txt com
/other/pckage/*.class main/pckage/*.class
 and the output is:
cmd--> added manifest
adding: com/other/pckage/OtherClass.class(in = 547) (out= 344)(deflated 37%)
adding: main/pckage/MainClass.class(in = 754) (out= 454)(deflated 39%)

Now we have successfully created the executable jar file in cmd.

Now write cmd--> java -jar myjar.jar
It will execute the main method of MainClass.java

And we can use that jar in any of our projects.

For more info click here..

Saturday, 23 June 2012