Sunday, 12 May 2013

Why Map is not a true Collection?

We saw what are Collections in Java. If you recall the diagram from that post Map does not form a part of Collection though it comes under Collection framework. In more technical terms Map interface does not implement Collection interface. Knowing this the question that naturally comes in mind is why so? Why can't Map be a part of Collection frame work? Let us see the explanation.

Reason for Map interface not extending Collection interface

  • If you look at the respective data structure you can easily guess why Map is not a part of Collection. Each Collection stores a single value where as a Map stores key-value pair. So methods in Collection interface are incompatible for Map interface.For example in Collection we have add(Object o). What would be such implementation in Map. It doesn't make sense to have such a method in Map. Instead we have a put(key,value)  method in Map.
  • Same argument goes for addAll(), remove(), removeAll() methods. So the main reason is the difference in the way data is stored in Map and Collections.
  • Also if you recall Collection interface implemented Iterable interface i.e any interface with .iterator() method should return an iterator which must allow us to iterate over the values stored in the Collection. Now what would such method return for a Map? Key iterator or a Value iterator? This does not make sense either.
There are ways in which we can iterate over keys and values stores in a Map and that is how it is a part of Collection framework.Do not get confuse here. Let me repeat this - Map is a part of Collection framework but it does not implement Collection interface. We will see in next few posts how Map works internally(that's really an interesting topic) and also how we manipulate data in it.

Just to recall the Collection framework refer to the following diagram -




A little fun with Linux command line!


Yes that's the picture I posted on LinuxForGeeks today on the special occasion of Mother day. Let me take this occasion to clarify that people using CLI(Command line interface) are not some geeks who know something special which common people don't. Once you start using CLI you will know how much fun it is. For now let me introduce some cool commands.

Here are some command you may enjoy in your spare time -

  1. fortune
    Fortune is a simple program that displays s pseudo random message from a database of quotations that first appeared in version 7 Uiux. Just type fortune in the CLI and see the various messages that are displayed.To install fortune type the following in CLI - sudo apt-get install fortune-mod

    Some examples are as follows -

    You get the point. For more info refer to its man page.Some options that you can use with the command are -

     
  2.  cowsay
    Cowsay is a program(written in Perl) which generates ASCII picture with of a cow with a message It can also generate pictures using pre-made images of other animals, such as Tux the Penguin, the Linux mascot.To install cowsay just type in CLI - sudo apt-get install cowsay

    Example -

    You can use -f  tux option to get a tux instead of a cow.
    That's not it. You can combine fortune and cowsay commands to have a bit more fun.Type the following in your CLI
    fortune | cowsay -f tux
  3.  
  4. espeak
    eSpeak is a compact open source software speech synthesizer for Linux.
    Just type  espeak 'Hello World' in your CLI and you will hear the voice saying the argument supplied(Hello World). This is the default program installed on Ubuntu.
    It can also read from a text file supplied with -f argument. For more info you can refer eSpeakCommands.

Saturday, 11 May 2013

Handling null in a Collection.

One of the general problem programmers land into is the NullPointerException. This post will mainly focus on how do we handle this null value. Specially in case of Collections what is the difference between and empty collection, a null Collection and a Collection containing a null value.

   Before we see how to handle null value remember that member(instance) variables are assigned default values if they are not initialized where as for local variable you need to explicitly initialize them before using them.So when we define a reference type as an instance variable it is by default set to null.Complete set of default values assigned to  instance variables are as follows -

Good Practice

Important point to note while comparing String literals is always put the literal to the L.H.S(Left hand side) of the == or equals() operator. For example -
        String typeOfOS;
        if("linux".equalsIgnoreCase(typeOfOS))
        {
            System.out.println("Very good choise of OS");
        }

Why so you might ask? Reason is simple if your variable typeOfOS is null it will throw a java.lang.NullPointerException.

Handling null in Collections

    It is important you understand the difference between a reference being null, Collection being empty and Collection containing null as an element.

  1. Reference being null

    List<String> operatingSystems = null;
    if(null == operatingSystems)
    {
        System.out.println("operatingSystems reference has not been initialized yet");
    }


    Explanation : No memory is allocated on heap in this case. This is just a reference that we have declared. We can check it for null as shown above.
  2. Collection being empty

            List<String> operatingSystem = new ArrayList<String>();
            if(operatingSystem.isEmpty())
            {
                System.out.println("List is empty");
            }


    Explanation : Here we create an object of List. Memory is allocated on the heap but there is no element in the List i.e the List is empty.You can check if Collection is empty or not by using .isEmpty() function.
  3. Collections containing null as an element


    Ground Work :
    We know List can have duplicate elements. This means a list can have multiple null values stored in it. Also in a Set duplicates are not allowed and hence only one null value is allowed. Never the less null is an acceptable value as an element in Collection. There are exceptions like EnumSet where null is not allowed but thats a rare usage.

            List<String> operatingSystem = new ArrayList<String>();
            operatingSystem.add(null);
            System.out.println("List is " + operatingSystem);
            if(operatingSystem.isEmpty())
            {
                System.out.println("List is empty");
            }
            else
            {
                System.out.println("List is not empty");
            }


    Output :



    Explanation : List is clearly not empty as we have added an element(null) to it. Whole point being null can be an element stores in a Collection.If you wish to remove null from the List you can simple say .remove(null).

Friday, 10 May 2013

How to find current Shell in Linux?

A very simple question that most of the Linux beginners have. Which shell am i using? How can i change it?When you write any shell script you need to specify which shell you want to use to execute your script(Given as an argument to Shebang).

    Be default on most of the distros the shell you have is BASH(Bourne-Again SHell). You can have other shells like CSH(C SHell), KSH (Korn SHell) etc.

Default BASH is as follows -


How to install other Shells?

  Let us first see how can we install other shells, change from BASH(default) to new shell and back.Lets say you want to install KSH (Korn SHell) . Simply type ksh in your console. If it is installed you will directly see $ symbol instead of your normal aniket@aniket-Compaq-610:~$  representation.If you do not get such a change you will see program not installed. So now you need to install it.
     Type sudo apt-get install ksh . Your ksh will now be installed. Again type in ksh which will bring you to korn shell with a $ symbol.To return back to your BASH shell simple type exit and enter.

KSH (Korn SHell) looks like below -

Now lets get to our main question. How do we figure out what shell are we using.

What Shell I am using?

There are  3 Ways in which users generally check their Shell. Let me explain each of them.Note all the snapshots here after will be executed in KSH (Korn SHell) so ksh must be the answer we are interested in.This is just FYI but point is to find what shell are we using.

  1. Just type echo $SHELL in your console(Not recommended method).

    What this will give is your default Shell not your current shell. So in both BASH as well as KSH you will get output as /bin/bashScreen shot for the same is -


  2. Type in echo $0 in your console(Simplest)

    $0 gives you name of the Shell or Shell script you are using. Screen shot -
  3. Type ps -p $$ in your console(the smart way)

    $$ symbol gives you the PID of the process running your current Shell. PS command gives you the PID of various running process(Try ps -ax to see yourself). -p argument take the specific PID you wish to see. So ps -p $$ whill give you your Current Shell with PID.
    Screen shot -
  4.  
     Play around with different Shells. Each have their own flavor. 

What is Shebang or Hashbang in Unix/Linux?

In a script if the first line consists of characters number sign and exclamation sign (i.e #!)  then such a sequence is know as Shebang or a Hashbang.

 This hashbang takes arguments. The first argument is always the path to the interpreter that will be used to interpret the script code  to follow.

     Suppose you are writing a shell script then the 1st line of your script would be something like #! /bin/sh . Code which will follow this will be interpreted by your shell(whatever you have usually this is Bourne shell).

   Another point to note that hashbang begins with a # character which is interpreted as comment in most of the scripts. So the corresponding interpreter will ignore this line.

Syntax

   Syntax is very simple
   #! interprter [optional arg]
Note this must be the 1st line of your script.

   The interpreter must usually be an absolute path to a  program that should be used to interpret rest of the script code.

Example

Some usage examples are - 
  • #!/bin/sh — Execute the file using sh, the Bourne shell, or a compatible shell
  • #!/bin/csh -f — Execute the file using csh, the C shell, or a compatible shell, and suppress the execution of the user’s .cshrc file on startup
  • #!/usr/bin/perl -T — Execute using Perl with the option for taint checks
  • #!/usr/bin/php — Execute the file using the PHP command line interpreter
  • #!/usr/bin/python -O — Execute using Python with optimizations to code
  • #!/usr/bin/ruby — Execute using Ruby

Purpose of a Hashbang

    Purpose is fairly straight forward. Lets say you have a perl script(GetIP.pl) and perl module is installed at /usr/bin/install/perl . Every time you wish to execute this file(from any directory you are in) you will need to give the absolute path where perl module is located to run the script /usr/bin/install/perl GetIP.pl  but using hashbang all you need to do is  GetIP.pl . It will execute the script using perl module directly.

What happens behind the scene(Magic number)?

The Shebang is actually a human readable instance of magic number in executable file. The magic byte string being 0x23 0x21 , the two character encoding in ASCII. The magic number is detected by "exec" family of functions which determine whether the image file is a script or an executable binary. The presence of  shebang will result in execution of specific executable, usually an interpreter for the script's language.
t> UA-39527780-1 back to top