Showing posts with label java programming. Show all posts
Showing posts with label java programming. Show all posts

Wednesday, 22 August 2012

How to create read only List, Map and Set in Java – unmodifiable example


Read only List, Map and Set in Java
Read only List means a List where you can not perform modification operations like addremove or set. You can only read from the List by using get method or by using Iterator of List, This kind of List is good for certain requirement where parameters are final and can not be changed. In Java you can use Collections.unModifiableList() method  to create read only List , Collections.unmodifiableSet() for creating read-only Set like read only HashSet and similarly creating a read only Map in Java, as shown in below example. Any modification in read only List will result in java.lang.UnSupportedOperationException in Java.  This read-only List example is based on Java 5 generics but also applicable  to other Java version like JDK 1.4 or JDK 1.3, just remove Generics code i.e. angle bracket which is not supported prior to Java 5. One common mistake programmer makes is that assuming fixed size List and read only List as same. As shown in our 3 example of converting Array to Array List , we can use Arrays.asList() method to create and initialized List at same line. List implementation returned by this method is fixed size and it doesn’t allow adding or removal of element but it is not read only because you can update objects by callingset(index) method. How to make a collection read only is also a popular Java collection interview question, which makes this Java collection tutorial even more important.

Read only List, Set and Map Example - Java

Example to create read only List Set and Map in JavaHere is sample Java program which demonstrate method of creating read only ListSet and Map in Java. You can make any ListSet or Map implementation as read only by following code example. Just remember that Collections.unModifiableList() , Collections.unModifiableSet() and Collections.unModifiableMap() method in Java. On read only List add, remove and set operation is not permitted, on read only Set you can not add or remove elements and in read only Map you can not put new entries or update existing entries. You can use same methods to convert any List implementation like ArrayListLinkedList or Vector to read only ArrayList , LinkedList and Vector in Java.

package example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * Java program to create read only List, Set and Map in Java. You can first create
 * a List or Set and than make it unmodifiable or read-only by
 * using  Collections.unmodifiableList() or Collections.unmodifiableSet() method.
 *
 * @author Javin Paul
 */

public class ReadOnlyListSetMap {
 
    public static void main(String args[]) {            
       
        // creating List in Java
        List<String> contents = new ArrayList<String>();
     
        // initializing List in Java
        contents.add("Example");
        contents.add("Tutorial");
        contents.add("Program");
     
     
        // Currently This List is not read only, you can add or remove elements from List
        contents.add("Tips"); //should not be allowed if List is read only.
     
        System.err.println("normal List in Java : " + contents);
     
        //creating readonly List from contents
        contents = Collections.unmodifiableList(contents);
     
        //java.lang.UnsupportedOperationException -- no modification in read only list
     
       //not allowed as it is read-only List in Java 
       contents.add("Can I add object into read only List - No");

       
        contents.remove("Example"); //remove not allowed in read only list
     
        //java.lang.UnSupportedOperation - List update not allowed
        contents.set(0"Can I override or set object in read-only Set - No");

     
        //Creating read only Set in Java
        //similar to read-only List you can also create a Set which is read only 
        //i.e. addition , removal and modification operation is not permitted on list
     
     
        //Creating a Set based on contents of List       
        Set<String> readOnlySet = new HashSet<String>(contents);
     
        System.out.println("original Set in Java : " + readOnlySet);

        //Set is not yet read-only you can still add elements into Set
        readOnlySet.add("Override");

        System.out.println("Set before making read only : " + readOnlySet);
     
        //making Set readonly in Java - no add remove or set operation permitted
        readOnlySet = Collections.unmodifiableSet(readOnlySet);
     
        //trying to add element in read only Set - java.lang.UnSupportedOperationException
        readOnlySet.add("You can not add element in read Only Set");
     
        //trying to remove element from read only set
        readOnlySet.remove("Example"); //you can not remove elements from read only Set
     
     
     
        // Creating read only Map in Java
        // Similar to List and Set you can also create read only or unmodifiable Map in Java
        // add , remove and override is not allowed on read only Map in Java
     
        Map<StringString> contries = new HashMap<StringString>();      
        contries.put("India""New Delhi");
     
        //Map is not read only yet, you can still add entries into
        contries.put("UK""London");
     
        System.out.println("Map in Java before making read only: " + contries);
     
        //Making Map read only in Java
        Map readOnlyMap = Collections.unmodifiableMap(contries);
       
        //you can not put a new entry in read only Map in Java
        readOnlyMap.put("USA""Washington"); //java.lang.UnSupportedOperation 
       
        //you can not remove keys from read only Map in Java
        readOnlyMap.remove("UK"); //java.lang.UnSupportedOperation
     
    }
 
}


That’s all on how to create read only ListSet and Map in Java. Its very easy to make any List implementation read only by wrapping it with Collections.unModifiableList(). Use same technique to convert any other Collection into read only in Java.

How to get environment variables in Java- Example Tutorial

Environment variables in Java
There are two ways to get environment variable in Java, by using System properties or by using System.getEnv(). System properties provides only limited set of predefined environment variables like java.classpath, for retriving Java Classpath or java.username  to get User Id which is used to run Java program etc but a more robust and platform independent way of getting environment variable in Java program on the other hand Sytem.getEnv() method provide access to all environment variables inside Java program but subject to introduce platform dependency if program relies on a particular environment variable. Sytem.getEnv() is overloaded method in Java API and if invoked without parameter it returns an unmodifiable String map which contains all environment variables and there values available to this Java process whileSystem.getEnv(String name) returns value of environment variable if exists or null. In our earlier posts we have seen How to get current directory in Java and  How to run shell command from Java program and in this Java tutorial we will see how to access environment variable in Java.

How to get environment variables in Java - Example

How to get value of environment variable in Java - example tutorialHere is a quick example on How to get environment variable in Java using System.getEnv() and System.getProperty(). Remember System.getEnv() return String map of all environment variables while System.getEnv(String name) only return value of named environment variable like JAVA_HOME will return PATH of your JDK installation directory.

/**
 * Java program to demonstrate How to get value of environment variables in Java.
 * Don't confuse between System property and Environment variable and there is separate
 * way to get value of System property than environment variable in Java, as shown in this
 * example.
 *
 * @author Javin Paul
 */


public class EnvironmentVariableDemo { 

    public static void main(String args[]){
 
      //getting username using System.getProperty in Java
       String user = System.getProperty("user.name") ;
       System.out.println("Username using system property: "  + user);
 
     //getting username as environment variable in java, only works in windows
       String userWindows = System.getenv("USERNAME");
       System.out.println("Username using environment variable in windows : "  + userWindows);
 
   
     //name and value of all environment variable in Java  program
      Map<StringString> env = System.getenv();
        for (String envName : env.keySet()) {
            System.out.format("%s=%s%n", envName, env.get(envName));
        }

    }
   
}

Output:Username using system property: harry
Username using environment variable in windows : harry
USERPROFILE=C:\Documents and Settings\harry
JAVA_HOME=C:\Program Files\Java\jdk1.6.0_20\
TEMP=C:\DOCUME~1\harry\LOCALS~1\Temp


Getting environment variable in Java – Things to remember
Java is platform independent language but there are many things which can make a Java program platform dependent e.g. using a native library. Since environment variables also vary from one platform to another e.g. from windows to Unix you need to be bit careful while directly accessing environment variable inside Java program. Here are few points which is worth noting :

1) Use system properties if value of environment variable is available via system property e.g. Username which is available using "user.name" system property. If you access it using environment variable directly you may need to ask for different variable as it may be different in Windows  e.g. USERNAME and Unix as USER.

2) Environment variables are case sensitive in Unix while case insensitive in Windows so relying on that can again make your Java program platform dependent.

3) System.getEnv() was deprecated in release JDK 1.3 in support of using System.getProperty() but reinstated again in JDK 1.5.

That's all on how to get environment variable in Java. Though you have convenient method like System.getEnv() which can return value of environment variable, its better to use System.getProperty()to get that value in a platform independent way, if that environment variable is available as system property in Java.