Sunday, February 12, 2012

What are Web Services ppt pdf documents WSDL XML example free download




What are Web Services ??

  1. Web services are based on the concept of service-oriented architecture (SOA). SOA is the latest evolution of distributed computing, which enables software components, including application functions, objects, and processes from different systems, to be exposed as services.
  2. Web services are loosely coupled software components delivered over Internet standard technologies.”
  3. Web services are self-describing and modular business applications that expose the business logic as services over the Internet through programmable interfaces and using Internet protocols for the purpose of providing ways to find, subscribe, and invoke those services.
  4. Web services can be developed as loosely coupled application components using any programming language, any protocol, or any platform. This facilitates delivering business applications as a service accessible to anyone, anytime, at any location, and using any platform.
  5. Web services are typically implemented based on open standards and technologies specifically leveraging XML. The XML-based standards and technologies, such as Simple Object Access Protocol (SOAP); Universal Description, Discovery, and Integration (UDDI); Web Services Definition Language (WSDL); and Electronic Business XML (ebXML), are commonly used as building blocks for Web services.

What are the differences between SAX and DOM parser xml parsing webservices



What are the differences between SAX and DOM parser


SAXDOM
Both SAX and DOM are used to parse the XML document. Both has advantages and disadvantages and can be used in our programming depending on the situation.
Parses node by nodeStores the entire XML document into memory before processing
Doesn’t store the XML in memoryOccupies more memory
We cant insert or delete a nodeWe can insert or delete nodes
Top to bottom traversingTraverse in any direction.
SAX is an event based parserDOM is a tree model parser
SAX is a Simple API for XMLDocument Object Model (DOM) API
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
 
doesn’t preserve commentspreserves comments
SAX generally runs a little faster than DOMSAX generally runs a little faster than DOM
If we need to find a node and doesn’t need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.

Saturday, February 4, 2012

Struts frame work action class validations tiles example jars download pdf docs FAQS


Q:        What is Struts?

A:     The core of the Struts framework is a flexible control layer based on standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages. Struts encouragesapplication architectures based on the Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm.

Struts provides its own Controller component and integrates with other technologies to provide the Model and the View. For the Model, Struts can interact with standard data access technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with JavaServer Pages, including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems.

The Struts framework provides the invisible underpinnings every professional web application needs to survive. Struts helps you create an extensible development environment for your application, based on published standards and proven design patterns.


Q:     What is Jakarta Struts Framework?

A:     Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of applicationof any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.


Q:     What is ActionServlet?

A:     The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.

Q:     How you will make available any Message Resources Definitions file to the Struts Framework Environment?

A:     T Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through <message-resources /> tag.

Example:

<message-resources parameter=\"MessageResources\" />.


Q:     What is Action Class?

A:     The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.


Q:     What is ActionForm?

A:     An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.


Q:     What is Struts Validator Framework?

A:     Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class.

The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.


Q:     Give the Details of XML files used in Validator Framework?

A:     The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.


Q:     How you will display validation fail errors on jsp page?

A:     Following tag displays all the errors:

<html:errors/>


Q:     How you will enable front-end validation based on the xml in validation.xml?

A:     The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code: <html:javascript formName=\"logonForm\" dynamicJavascript=\"true\" staticJavascript=\"true\" /> generates the client side java script for the form \"logonForm\" as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script.


Q:     How to get data from the velocity page in a action class?

A:     We can get the values in the action classes by using data.getParameter(\"variable name defined in the velocity page\");

Thursday, February 2, 2012

JSP Faqs material tutorial doc pdf ppt interview question download vidoes question


1. What is the difference between JSP and Servlets ?
JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc.

2. What is difference between custom JSP tags and beans?
Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components: the tag handler class that defines the tag’s behavior ,the tag library descriptor file that maps the XML element names to the tag implementations and the JSP file that uses the tag library
JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags
Custom tags and beans accomplish the same goals — encapsulating complex behavior into simple and accessible forms. There are several differences:
Custom tags can manipulate JSP content; beans cannot. Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans. Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page. Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

3. What are the different ways for session tracking?
Cookies, URL rewriting, HttpSession, Hidden form fields

4. What mechanisms are used by a Servlet Container to maintain session information?
Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information

5. Difference between GET and POST
In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 255 characters, not secure, faster, quick and easy. The data is submitted as part of URL.
In POST data is submitted inside body of the HTTP request. The data is not visible on the URL and it is more secure.

6. What is session?
The session is an object used by a servlet to track a user’s interaction with a Web application across multiple HTTP requests. The session is stored on the server.

7. What is servlet mapping?
The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to Servlets.

8. What is servlet context ?
The servlet context is an object that contains a information about the Web application and container. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use.

9. What is a servlet ?
servlet is a java program that runs inside a web container.

10. Can we use the constructor, instead of init(), to initialize servlet?
Yes. But you will not get the servlet specific things from constructor. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructor a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.

12. How many JSP scripting elements are there and what are they?
There are three scripting language elements: declarations, scriptlets, expressions.

13. How do I include static files within a JSP page?
Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase.

14. How can I implement a thread-safe JSP page?
You can make your JSPs thread-safe adding the directive <%@ page isThreadSafe="false" % > within your JSP page.

15. What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?
In request.getRequestDispatcher(path) in order to create it we need to give the relative path of the resource. But in resourcecontext.getRequestDispatcher(path) in order to create it we need to give the absolute path of the resource.

16. What are the lifecycle of JSP?
When presented with JSP page the JSP engine does the following 7 phases.
Page translation: -page is parsed, and a java file which is a servlet is created.
Page compilation: page is compiled into a class file
Page loading : This class file is loaded.
Create an instance :- Instance of servlet is created
jspInit() method is called
_jspService is called to handle service calls
_jspDestroy is called to destroy it when the servlet is not required.

17. What are context initialization parameters?
Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application.

18. What is a Expression?
Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed. This will be included in the service method of the generated servlet.

19. What is a Declaration?
It declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as semicolons separate them. The declaration must be valid in the scripting language used in the JSP file. This will be included in the declaration section of the generated servlet.

20. What is a Scriptlet?
A scriptlet can contain any number of language statements, variable or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a . Generally a scriptlet can contain any java code that are valid inside a normal java method. This will become the part of generated servlet’s service method.

Wednesday, February 1, 2012

Core Java FAQ's interview download free videos ppt doc pdf online tutorials


Q:
What is the difference between an Interface and an Abstract class?
A:
An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.



Q:
What is the purpose of garbage collection in Java, and when is it used?
A:
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.


Q:
Describe synchronization in respect to multithreading.
A:
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors. 


Q:
Explain different way of using thread?
A:
The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.


Q:
What are pass by reference and passby value?
A:
Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed. 


Q:
What is HashMap and Map?
A:
Map is Interface and Hashmap is class that implements that.


Q:
Difference between HashMap and HashTable?
A:
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.


Q:
Difference between Vector and ArrayList?
A:
Vector is synchronized whereas arraylist is not.


Q:
Difference between Swing and Awt?
A:
AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.


Q:
What is the difference between a constructor and a method?
A:
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.


Q:
What is an Iterator?
A:
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.


Q:
State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
A:
public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.


Q:
What is an abstract class?
A:
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.


Q:
What is static in java?
A:
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.


Q:
What is final?
A:
A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

Saturday, January 21, 2012

Java exception handling examples throw throws try catch finally material ppt



Exceptions in Java


Throwable Class


The Throwable class provides a String variable that can be set by the subclasses to provide a detail message that provides more information of the exception occurred. All classes of throwables define a one-parameter constructor that takes a string as the detail message.


The class Throwable provides getMessage() function to retrieve an exception. It has a printStackTrace() method to print the stack trace to the standard error stream. Lastly It also has a toString() method to print a short description of the exception. For more information on what is printed when the following messages are invoked, please refer the java docs.


Syntax


String getMessage()


void printStackTrace()


String toString()


Class Exception


The class Exception represents exceptions that a program faces due to abnormal or special conditions during execution. Exceptions can be of 2 types: Checked (Compile time Exceptions)/ Unchecked (Run time Exceptions).


Class RuntimeException


Runtime exceptions represent programming errors that manifest at runtime. For example ArrayIndexOutOfBounds, NullPointerException and so on are all subclasses of the java.lang.RuntimeException class, which is a subclass of the Exception class. These are basically business logic programming errors.


Class Error


Errors are irrecoverable condtions that can never be caught. Example: Memory leak, LinkageError etc. Errors are direct subclass of Throwable class.


Checked and Unchecked Exceptions


Checked exceptions are subclass’s of Exception excluding class RuntimeException and its subclasses. Checked Exceptions forces programmers to deal with the exception that may be thrown. Example: Arithmetic exception. When a checked exception occurs in a method, the method must either catch the exception and take the appropriate action, or pass the exception on to its caller


Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. Unchecked exceptions , however, the compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause. In fact, the programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBounds Exception. They are either irrecoverable (Errors) and the program should not attempt to deal with them, or they are logical programming errors. (Runtime Exceptions). Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.


Exception Statement Syntax


Exceptions are handled using a try-catch-finally construct, which has the Syntax


try {
<code>
} catch (<exception type1> <parameter1>) { // 0 or more
<statements>
}
} finally { // finally block
<statements>
}


Try Block
The java code that you think may produce an exception is placed within a try block for a
suitable catch block to handle the error.




If no exception occurs the execution proceeds with the finally block else it will look for the
matching catch block to handle the error. Again if the matching catch handler is not found execution
proceeds with the finally block and the default exception handler throws an exception.. If an exception is
generated within the try block, the remaining statements in the try block are not executed.


Catch Block
Exceptions thrown during execution of the try block can be caught and handled in a catch block. On exit from a catch block, normal execution continues and the finally block is executed
(Though the catch block throws an exception).


Finally Block
A finally block is always executed, regardless of the cause of exit from the try block, or whether any catch block was executed. Generally finally block is used for freeing resources, cleaning up, closing connections etc. If the finally clock executes a control transfer statement such as a return or a break statement, then this control
statement determines how the execution will proceed regardless of any return or control statement present in the try or catch.

Wednesday, January 11, 2012

Core java Collection framework material tutorial PDF free download online


 Java Collections and Generics

  • The Java Collections Framework
  • Java Generics

13.1. The Java Collections Framework

  • Java arrays have limitations.
    • They cannot dynamically shrink and grow.
    • They have limited type safety.
    • Implementing efficient, complex data structures from scratch would be difficult.
  • The Java Collections Framework is a set of classes and interfaces implementing complex collection data structures.
    • collection is an object that represents a group of objects.
  • The Java Collections Framework provides many benefits:
    • Reduces programming effort (already there)
    • Increases performance (tested and optimized)
    • Part of the core API (available, easy to learn)
    • Promotes software reuse (standard interface)
    • Easy to design APIs based on generic collections
The Java Collections Framework consists of:

Collection interfaces
Collection, List, Set, Map, etc.
General-purpose implementations
ArrayList, LinkedList, HashSet, HashMap, etc.
Special-purpose implementations
designed for performance characteristics, usage restrictions, or behavior
Concurrent implementations
designed for use in high-concurrency contexts
Wrapper implementations
adding synchronization, immutability, etc.
Abstract implementations
building blocks for custom implementations
Algorithms
static methods that perform useful functions, such as sorting or randomizing a collection
Infrastructure
interfaces to support the collections
Array utilities
static methods that perform useful functions on arrays, such as sorting, initializing, or converting to collections
More information on the Java Collections Framework is available at:http://download.oracle.com/javase/tutorial/collections/index.html

13.2. The Collection Interface

  • java.util.Collection is the root interface in the collections hierarchy.
    • It represents a group of Objects.
    • Primitive types (e.g., int) must be boxed (e.g., Integer) for inclusion in a collection.
    • More specific collection interfaces (e.g., List) extend this interface.
  • The Collection interface includes a variety of methods:
    • Adding objects to the collection: add(E)addAll(Collection)
    • Testing size and membership: size()isEmpty()contains(E),containsAll(Collection)
    • Iterating over members: iterator()
    • Removing members: remove(E)removeAll(Collection)clear(),retainAll(Collection)
    • Generating array representations: toArray()toArray(T[])
The Collection interface does not say anything about:
  • the order of elements
  • whether they can be duplicated
  • whether they can be null
  • the types of elements they can contain
This interface is typically used to pass collections around and manipulate them in the most generic way.

13.3. Iterating Over a Collection

  • An iterator is an object that iterates over the objects in a collection.
  • java.util.Iterator is an interface specifying the capabilities of an iterator.
    • Invoking the iterator() method on a collection returns an iterator object that implements Iterator and knows how to step through the objects in the underlying collection.
  • The Iterator interface specifies the following methods:
    • hasNext() - Returns true if there are more elements in the collection; false otherwise
    • next() - Returns the next element
    • remove() - Removes from the collection the last element returned by the iterator
For example, to print all elements in a collection:
private static void print(Collection c) {
    Iterator i = c.iterator();
    while (i.hasNext()) {
        Object o = i.next();
        System.out.println(o);
    }
}
This can also be written as:
private static void print(Collection c) {
    for (Iterator i = c.iterator(); i.hasNext(); ) {
        System.out.println(i.next());
    }
}
And in Java 5, the Iterator can be used implicitly thanks to for-each:
private static void print(Collection c) {
    for (Object o : c) {
        System.out.println(o);
    }
}

13.4. The List Interface

  • The java.util.List Interface extends the Collection interface.
  • The List interface declares methods for managing an ordered collection of object (asequence). You can:
    • Control where each element is inserted in the list
    • Access elements by their integer index (position in the list)
    • Search for elements in the list
    • Insert duplicate elements and null values, in most List implementations
[Tip]Tip
Especially if you’re dynamically resizing a collection of object, favor using a List over a Java array.
  • Some additional methods provided by List include:
    • add(int index, E element) — Insert an element at a specific location (without an index argument, new elements are appended to the end)
    • get(int index) — Return an element at the specified location
    • remove(int index) — Remove an element at the specified location
    • set(int index, E element) — Replace the element at the specified location
    • subList(int fromIndex, int toIndex) — Returns as a List a modifiable view of the specified portion of the list (that is, changes to the view actually affect the underlying list)

13.5. Classes Implementing List

  • Java provides several classes that implement the List interface.
  • Two are used most commonly:

    java.util.ArrayList
    An ArrayList is usually your best bet for a List if the values remain fairly static once you’ve created the list. It’s more efficient than a LinkedList for random access.
    java.util.LinkedList
    A LinkedList provides better performance than an ArrayList if you’re frequently inserting and deleting elements, especially from the middle of the collection. But it’s slower than an ArrayList for random-access.


In the following example, notice the use of the java.util.Collections.sort() static method, which does an in-place sort of the elements in a List:
package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * This program reads arguments passed to it from the command-line
 * or the lines from STDIN, sorts them, and writes the result to STDOUT.
 */
public class Sort {
    public static void main(String[] args) throws IOException {
        if (args.length > 0) {
            Arrays.sort(args);
            for (int i = 0; i < args.length; i++) {
                System.out.println(args[i]);
            }
        } else {
            List lines = new ArrayList();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    System.in));
            String line = null;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
            Collections.sort(lines);
            for (Iterator i = lines.iterator(); i.hasNext();) {
                System.out.println(i.next());
            }
        }
    }
}

13.6. The Set and SortedSet Interfaces

  • The java.util.Set Interface extends the Collection interface.
  • The Set interface declares methods for managing a collection of objects that contain no duplicates.
    • The basic Set interface makes no guarantee of the order of elements.
    • A Set can contain at most one null element.
    • Mutable elements should not be changed while in a Set.
  • The Set interface adds no methods beyond those of the Collection interface.
    • The Set interface simply enforces behavior of the collection.
  • The java.util.SortedSet interface extends Set so that elements are automatically ordered.
    • A SortedSet Iterator traverses the Set in order.
    • A SortedSet also adds the methods first()last()headSet()tailSet(), andsubSet()

13.7. Classes Implementing Set

  • Java provides several classes that implement the Set interface, including:
java.util.HashSet:: A hash table implementation of the Set interface. The best all-around implementation of the Set interface, providing fast lookup and updates.

java.util.LinkedHashSet
A hash table and linked list implementation of the Set interface. It maintains the insertion order of elements for iteration, and runs nearly as fast as a HashSet.
java.util.TreeSet
A red-black tree implementation of the SortedSet interface, maintaining the collection in sorted order, but slower for lookups and updates.
package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * This program computes a unique set of elements passed to it either from
 * command line (as arguments) or from STDIN (as lines).
 *
 * This demonstrates the use of Sets.
 */
public class Unique {

    public static void main(String[] args) throws IOException {
        Set unique = new HashSet(); // replace with TreeSet to get them sorted
        if (args.length > 0) {
            unique.addAll(Arrays.asList(args));
        } else {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    System.in));
            String line = null;
            while ((line = reader.readLine()) != null) {
                unique.add(line);
            }
        }
        for (Iterator i = unique.iterator(); i.hasNext();) {
            System.out.println(i.next());
        }
    }
}

13.8. The Queue Interface

  • The java.util.Queue interface is a collection designed for holding elements prior to processing.
    • Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations.
    • Queues can implement FIFO (queue), LIFO (stack), and priority ordering.
    • Queues generally do not accept null elements.
  • Queue operations include:
    • Inserting elements: add() and offer()
    • Removing and returning elements: remove() and poll()
    • Returning elements without removal: element() and peek()
  • The java.util.concurrent.BlockingQueue interfaces declare additional blocking put() andtake() methods, designed for concurrent access by multiple threads.
General-purpose Queue implementations:
  • java.util.LinkedList
  • java.util.PriorityQueue
Concurrency-specific BlockingQueue implementations:
  • java.util.concurrent.ArrayBlockingQueue
  • java.util.concurrent.ConcurrentLinkedQueue
  • java.util.concurrent.DelayQueue
  • java.util.concurrent.LinkedBlockingQueue
  • java.util.concurrent.PriorityBlockingQueue
  • java.util.concurrent.SynchronousQueue

13.9. The Map Interface

  • The java.util.Map interface does not extend the Collection interface!
  • A Map is a collection that maps key objects to value objects.
    • A Map cannot contain duplicate keys
    • Each key can map to at most one value.
  • The Map interface methods include:
    • Adding key-value pairs to the collection: put(K, V)putAll(Map)
    • Retrieving a value by its key: get(K)
    • Testing size: size()isEmpty()
    • Testing membership: containsKey(K)containsValue(V)
    • Removing members: remove(K)clear()
  • The java.util.SortedMap interface extends Map so that elements are automatically ordered by key.
    • Iterating over a SortedMap iterates over the elements in key order.
    • A SortedMap also adds the methods firstKey()lastKey()headMap()tailMap(), andsubMap()

13.10. Retrieving Map Views

  • You can also also retrieve collections as modifiable views from the Map representing the keys (keySet()), the values (values()), and a Set of key-value pairs (entrySet()).
    • These collections are used typically to iterate over the Map elements.
    • These collections are backed by the Map, so changes to the Map are reflected in the collection views and vice-versa.
  • Iterating over Map elements is done typically with a Set of objects implementing thejava.util.Map.Entry interface.
    • You retrieve the Set of Map.Entry objects by invoking Map.entrySet().
    • To iterate over the Map elements using an explicit Iterator:
      for (Iterator i = map.entrySet().iterator; i.hasNext(); ) {
          Map.Entry entry = (Map.Entry) i.next();
          System.out.println( entry.getKey() + ":\t" + entry.getValue() );
      }
    • To iterate over the Map elements using the for-each syntax:
      for ( Map.Entry entry: map.entrySet() ) {
          System.out.println(entry.getKey() + ":\t" + entry.getValue());
      }

13.11. Classes Implementing Map

  • Java provides several classes that implement the Map interface, including:
java.util.HashMap:: A hash table implementation of the Map interface. The best all-around implementation of the Map interface, providing fast lookup and updates.

java.util.LinkedHashMap
A hash table and linked list implementation of the Map interface. It maintains the insertion order of elements for iteration, and runs nearly as fast as a HashMap.
java.util.TreeMap
A red-black tree implementation of the SortedMap interface, maintaining the collection in sorted order, but slower for lookups and updates.
package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * This program computes the frequency of words passed to it either as command
 * line arguments or from STDIN. The result is written back to STDOUT.
 *
 * This demonstrates the use of Maps.
 */
public class WordFrequency {

    public static void main(String[] args) throws IOException {
        // replace with TreeMap to get them sorted by name
        Map wordMap = new HashMap();
        if (args.length > 0) {
            for (int i = 0; i < args.length; i++) {
                countWord(wordMap, args[i]);
            }
        } else {
            getWordFrequency(System.in, wordMap);
        }
        for (Iterator i = wordMap.entrySet().iterator(); i.hasNext();) {
            Map.Entry entry = (Map.Entry) i.next();
            System.out.println(entry.getKey() + " :\t" + entry.getValue());
        }

    }

    private static void getWordFrequency(InputStream in, Map wordMap)
            throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        int ch = -1;
        StringBuffer word = new StringBuffer();
        while ((ch = reader.read()) != -1) {
            if (Character.isWhitespace(ch)) {
                if (word.length() > 0) {
                    countWord(wordMap, word.toString());
                    word = new StringBuffer();
                }
            } else {
                word.append((char) ch);
            }
        }
        if (word.length() > 0) {
            countWord(wordMap, word.toString());
        }
    }

    private static void countWord(Map wordMap, String word) {
        Integer count = (Integer) wordMap.get(word);
        if (count == null) {
            count = new Integer(1);
        } else {
            count = new Integer(count.intValue() + 1);
        }
        wordMap.put(word, count);
    }
}

13.12. The Collections Class

  • The java.util.Collections class (note the final "s" ) consists exclusively of static methods that operate on or return collections. Features include:
    • Taking a collection and returning an unmodifiable view of the collection
    • Taking a collection and returning a synchronized view of the collection for thread-safe use
    • Returning the minimum or maximum element from a collection
    • Sorting, reversing, rotating, and randomly shuffling List elements
  • Several methods of the Collections class require objects in the collection to be comparable.
    • The object class must implement the java.lang.Comparable interface.
    • The object class must provide an implementation of the compareTo() method, which a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
[Note]Note
There are several requirements for proper implementation of the compareTo()method. See the reference documentation for more information. The bookEffective Java, 2nd ed., by Joshua Bloch also has excellent information on the requirements and pitfalls of proper implementation of the compareTo() method.

13.13. Type Safety in Java Collections

  • The Java Collections Framework was designed to handle objects of any type.
    • In Java 1.4 and earlier they used Object as the type for any object added to the collection.
    • You had to explicitly cast the objects to the desired type when you used them or else you would get compile-time errors.
      Employee e = (Employee) list.get(0);
    • Worse yet, if you were dealing with a collection of objects, say of type Dog, and then accidentally added an object of an incompatible type, say a Cat, your code could eventually try to cast the object to the incompatible type, resulting in a runtime exception.
Java arrays actually have a similar polymorphism problem that can result in runtime exceptions:
package com.markana.demo;

abstract class Animal {
    abstract public void speak();

    public void identify() {
        System.out.println("I'm an animal.");
    }
}

class Dog extends Animal {
    @Override
    public void speak() {
        System.out.println("woof");
    }

    @Override
    public void identify() {
        System.out.println("I'm a Dog.");
    }
}

class Cat extends Animal {
    @Override
    public void speak() {
        System.out.println("meow");
    }

    @Override
    public void identify() {
        System.out.println("I'm a Cat.");
    }
}

package com.markana.demo;

/** Demonstration that arrays are not completely type-safe
 * @author Ken Jones
 *
 */
public class ArrayTypeError {

    public static void main(String[] args) {
        // Create an array of three anonymous dogs
        Dog[] kennel = { new Dog(), new Dog(), new Dog()};

        // Let them all speak
        for (Dog d: kennel) d.speak();

        // Dogs are Objects, so this should work
        Object[] things = kennel;

        /* A Cat is an Object, so we should be able to add one to the
         * things array. Note that the following does NOT cause a
         * compiler error! Instead it throws a RUNTIME exception,
         * ArrayStoreException.
         */
        things[0] = new Cat();
    }

}

13.14. Java Generics

  • Java Generics, introduced in Java 5, provide stronger type safety.
  • Generics allow types to be passed as parameters to class, interface, and method declarations. For example:
    List<Employee> emps = new ArrayList<Employee>();
  • The <Employee> in this example is a type parameter.
    • With the type parameter, the compiler ensures that we use the collection with objects of a compatible type only.
    • Another benefit is that we won’t need to cast the objects we get from the collection:
      Employee e = emps.get(0);
    • Object type errors are now detected at compile time, rather than throwing casting exceptions at runtime.

13.15. Generics and Polymorphism

  • What can be confusing about generics when you start to use them is that collections of a type are not polymorphic on the type.
    • That is, you can not assign a List<String> to a reference variable of type List<Object>(and by extension, pass a List<String> as an argument to a method whose parameter is type List<Object>); it results in a compiler error.
    • Why? If allowed, we could then add objects of an incompatible type to the collection through the more “generic” typed reference variable.
  • So if you define a printCollection() to accept a parameter typed List<Person>, you can pass only List<Person> collections as arguments.
    • Even if Employee is a subclass of Person, a List<Employee> can’t be assigned to aList<Person>.
Here’s an illustration of how type parameters are not polymorphic for collections:
package com.markana.demo;

import java.util.*;

public class GenericsTypeError {
    public static void main( String[] args) {
        // Create a List of Dog objects
        List<Dog> kennel = new ArrayList<Dog>();

        // Adding a Dog is no problem
        kennel.add( new Dog() );

        // The following line results in a compiler error
        List<Object> objs = kennel;

        // Because if it were allowed, we could do this
        objs.add( new Cat() );

        // And now we've got a Cat in our List of Dogs
    }
}

13.16. Type Wildcards

  • The ? type parameter wildcard is interpreted as “type unknown.”
    • So declaring a variable as List<?> means that you can assign a List of any type of object to the reference variable.
    • However, once assigned to the variable, you can’t make any assumptions about the type of the objects in the list.
  • So defining your method as printCollection(List<?> persons) means that it can accept a List of any type.
    • But when invoked, you can’t make any assumptions as to the type of objects that the list contains.
    • Remember, ? is “type unknown”.
    • At best, you know that everything can be treated as an Object.
package com.markana.demo;

import java.util.*;

public class GenericsWildcardExample1 {

    public static void main( String[] args) {
        // Create a List of Dog objects
        List<Dog> kennel = new ArrayList<Dog>();

        // Adding a Dog is no problem
        kennel.add( new Dog() );

        // The following line compiles without error
        List<?> objs = kennel;

        /*
         * But now we can't make any assumptions about the type of
         * objects in the objs List. In fact, the only thing that
         * we can safely do with them is treat them as Objects.
         * For example, implicitly invoking toString() on them.
         */

        for (Object o: objs) {
            System.out.println("String representation: " + o);
        }

    }
}

13.17. Qualified Type Wildcards

  • Declaring a variable or parameter as List<? extends Person>, says that the list can be of all Person objects, or all objects can be of (the same) subclass of Person.
    • So you can access any existing object in the List as a Person.
    • However, you can’t add new objects to the List.
    • The list might contain all Person objects… or Employee objects, or Customer objects, or objects of some other subclass of Person. You’d be in trouble if you could add a Customer to a list of Employees.
  • Another type wildcard qualifier is super.
    • List<? super Employee> means a List of objects of type Employee or some supertype of Employee.
    • So the type is “unknown,” but in this case it could be Employee, Person, or Object.
    • Because you don’t know which, for “read” access the best you can do is use only Object methods.
    • But you can add new Employee objects to the list, because polymorphism allows the Employee to be treated as a Person or Object as well.
  • Both extends and super can be combined with the wildcard type.
package com.markana.demo;

import java.util.*;

public class GenericsWildcardExample2 {

    public static void main( String[] args) {
        // Create a List of Dog objects
        List<Dog> kennel = new ArrayList<Dog>();

        // Adding a Dog is no problem
        kennel.add( new Dog() );

        /*
         * We can assign to objs a reference to any List as long
         * as it contains objects of type Animal or some subclass
         * of Animal.
         */

        List<? extends Animal> objs = kennel;

        /*
         * Now we know that the objects in the objs List are
         * all Animals or all the same subclass of Animal. So
         * we can safely access the existing objects as Animals.
         * For example, invoking identify() on them.
         */

        for (Animal o: objs) {
            o.identify();
        }

        /*
         * However, it would be a compilation error to try to
         * add new objects to the list through objs. We don't know
         * what type of objects the List contains. They might be
         * all Dogs, or all Cats, or all "generic" Animals.
         */
    }
}

13.18. Generic Methods

  • generic method is one implemented to work with a variety of types.
    • The method definition contains one or more type parameters whose values are determined when the method is invoked.
    • Type parameters are listed within <> after any access modifiers and before the method return type.
    • You can use any identifier for a type parameter, but single letters like <T> are used most often.
  • For example:
    static <T> void addToCollection(T p, Collection<T> c) {
        c.add(p);
    }
    • In this example, the object p and the objects in the collection c must all be the same type.
  • You can use type wildcards, extends, and super in generic method definitions as well.
package com.markana.demo;

import java.util.*;

public class GenericsWildcardExample3 {

    public static <T> void add1( T obj, Collection<? super T> c) {
        c.add(obj);
    }

    public static <U, T extends U> void add2( T obj, Collection<U> c) {
        c.add(obj);
    }

    public static void main( String[] args) {

        // Create a List of Cat and Dog objects
        List<Animal> menagerie = new ArrayList<Animal>();

        // Add a Cat and a Dog
        menagerie.add( new Cat() );
        menagerie.add( new Dog() );

        // And now let's try using our generic methods to add objects
        add1( new Cat(), menagerie);
        add2( new Dog(), menagerie);

        for (Animal o: menagerie) {
            o.identify();
        }

    }
}
Related Posts Plugin for WordPress, Blogger...