about me

EL Expression

| 31 thg 1, 2010
  • JSF allows for converting and validating component (????)data,propagating component data to objects
  • For instance, you can provide an EL resolver (????)that intercepts objects with the name customer, so that ${customer} returns a value in the EL resolver instead.However, you cannot override implicit objects in this way

Generics in Java – Part II

| 30 thg 1, 2010

Abstract

In Part-I, we showed the benefits and usage of Generics in Java 5. In this part (Part-II), we discuss how it is implemented in Java, and we delve into a number of issues with it. In Part-III, we will discuss the problems with mixing generic and non-generic code, and the issues with converting a non-generic legacy code to Generics.

Unchecked Warning

The Java compiler will warn you if it can’t verify type-safety. You would see this if you mix generic and non-generic code (which is not a good idea). Developing applications while leaving these kinds of warnings unattended is a risk. It is better to treat warnings as errors.
Consider the following example:
 Collapse
public class Test
{
    public static void foo1(Collection c)
    {
    }

    public static void foo2(Collection c)
    {
    }

    public static void main(String[] args)
    {
        Collection coll = new ArrayList();
        foo1(coll);

        ArrayList lst = new ArrayList();
        foo2(lst);
    }
}
You have a method foo1 which accepts a traditional Collection as parameter. Method foo2, on the other hand, accepts a Generics version of the Collection. You are sending an object of the traditional ArrayList to methodfoo2. Since the ArrayList may contain objects of different types, within the foo2 method, the compiler is not able to guarantee that the Collection<Integer> will contain only instances of Integer. The compiler, in this case, issues a warning as shown below:
 Collapse
Warning:  line (22) [unchecked] unchecked conversion found : 
          java.util.ArrayList required: 
java.util.Collection
While getting this warning is certainly better than not being alerted about the potential problem, it would have been better if it had been an error instead of a warning. Use the compilation flag –Xlint to make sure you do not overlook this warning.
There is another problem. In the main method, you are sending a generic Collection of Integer to the methodfoo1. Even though the compiler does not complain about this, this is dangerous. What if within the foo1 method you add objects of types other than Integer to the collection? This will break the type-safety.
You may be wondering how in the first place the compiler even allowed you to treat a generic type as a traditional type. Simply put, the reason is, there is no concept of Generics at the byte code level. I will delve into the details of this in the “Generics Implementation” section.

Restrictions

There are a number of restrictions when it comes to using generics. You are not allowed to create an array of generic collections. Any array of collection of wildcards is allowed, but is dangerous from the type-safety point of view. You can’t create a generic of a primitive type. For example, ArrayList is not allowed. You are not allowed to create parameterized static fields within a generic class, or have static methods with parameterized types as parameters. For instance, consider the following:
 Collapse
class MyClass
{
    private Collection myCol1; // OK
    private static Collection myCol2; // ERROR
}
Within a generic class, you can’t instantiate an object or an array of objects of a parameterized type. For instance, if you have a generic class MyClass<T>, within a method of that class, you can’t write:
 Collapse
new T();
or
 Collapse
new T[10];
You may throw an exception of generic type; however, in the catch block, you have to use a specific type instead of the generic.
You may inherit your class from another generic class; however, you can’t inherit from a parametric type. For instance, while:
 Collapse
class MyClass2 extends MyClass
{
}
is OK,
 Collapse
class MyClass2 extends T
{
}
is not.
You are not allowed to inherit from two instantiations of the same generic type. For example, while:
 Collapse
class MyList implements MyCollection
{
    //...
}
is OK,
 Collapse
class MyList implements MyCollection, MyCollection
{
    //...
}
is not.
What is the reason for these restrictions? These restrictions largely arise from the way generics are implemented. By understanding the mechanism used to implement generics in Java, you can see where these restrictions come from and why they exist.

Generics Implementation

Generics is a Java language level feature. One of the design goals of Generics was to keep binary compatibility at the byte code level. By requiring no change to JVM, and maintaining the same format of the class files (byte code), you can easily mix Generics code and non-Generics code. However, this comes at a price. You may end up loosing what generics are intended to provide in the first place – type-safety.
Does it matter that generics are at the language level and not really at the byte code level? There are two reasons to be concerned. One, if this is only a language level feature, what would happen if and when other languages are expected to run on the JVM? If the other languages to run on JVM are dynamic languages (Groovy, Ruby, Python, …), then it may not be a big deal. However, if you attempt to run a strongly typed language on JVM, this may be an issue. Second, if this is simply a language level feature (one heck of a macro essentially), then it would be possible to pass in correct types at runtime, using Reflection, for instance.
Unfortunately, Generics in Java does not provide adequate type-safety. It does not fully serve what it was created for.

Erasure

So, if Generics is a language level feature, what happens when you compile your Generics code? Your code is striped out of all parametric types, and each reference to a parametric type is replaced with a class (typically Object or something more specific). This process is given a fancy name – type erasure.
According to the documentation: “The main advantage of this approach is that it provides total interoperability between generic code and legacy code that uses non-parameterized types (which are technically known as raw types). The main disadvantages are that parameter type information is not available at run time, and that automatically generated casts may fail when interoperating with ill-behaved legacy code. There is, however, a way to achieve guaranteed run-time type safety for generic collections even when interoperating with ill-behaved legacy code.”
While this provides interoperability with generic and non-generic code, it unfortunately compromises type-safety. Let’s look at the effect of erasure on your code.
Consider the example code:
 Collapse
class MyList
{
    public T ref;
}
By running javap –c, you can look at what’s in the byte code as shown below:
 Collapse
javap -c MyList
Compiled from "Test.java"
class com.agiledeveloper.MyList extends java.lang.Object{
public java.lang.Object ref;

com.agiledeveloper.MyList();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."":()V
   4:   return
The type T of the ref member of the class has been erased to (replaced by) the type Object.
Not all types are always erased to or replaced by Object. Take a look at this example:
 Collapse
class MyListextends Vehicle>
{
    public T ref;
}
In this case, the type T is replaced by Vehicle as shown below:
 Collapse
javap -c MyList
Compiled from "Test.java"
class com.agiledeveloper.MyList extends java.lang.Object{
public com.agiledeveloper.Vehicle ref;

com.agiledeveloper.MyList();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."":()V
   4:   return
Now, consider the example:
 Collapse
class MyListextends Comparable>
{
    public T ref;
}
Here the type T is replaced by the Comparable interface.
Finally, if you use the multi-bound constraint, as in:
 Collapse
class MyListextends Vehicle & Comparable>
{
    public T ref;
}
then the type T is replaced by Vehicle. The first type in the multi-bound constraint is used as the type in erasure.

Effect of Erasure

Let’s look at the effect of erasure on a code that uses a generic type. Consider the example:
 Collapse
ArrayList lst  = new ArrayList();
lst.add(new Integer(1));
Integer val = lst.get(0);
This is translated into:
 Collapse
ArrayList lst = new ArrayList();
lst.add(new Integer(1));
Integer val = (Integer) lst.get(0);
When you assign lst.get(0) to val, type casting is performed in the translated code. If you were to write the code without using generics, you would have done the same. Generics in Java, in this regards, simply acts as a syntax sugar.

Where are We?

We have discussed how generics are treated in Java. We looked at the extent to which type-safety is provided. We will discuss some more issues related to generics in the next part (Part III).

Conclusion

Generics in Java were created to provide type-safety. They are implemented only at the language level. The concept is not carried down to the byte code level. It was designed to provide compatibility with legacy code. As a result, generics lack what they were intended for – type-safety.

IT sẽ cho bạn

|
cung cấp dịch vụ tư vấn, kỹ thuật công nghệ, dịch vụ y tế, dược phẩm, công nghệ sinh học tại Bắc Mỹ, châu Âu và Nhật Bản

elementObject.removeAttribute("attributeName", flag);

| 19 thg 1, 2010
elementObject.removeAttribute("attributeName", flag);
Where "attributeName" is the name of the attribute which is to be removed and flag is the value which customizes the functionality of this removeAttribute() method. The flag value may be 0, 1 or and it is optional. Following are the meanings of their flag's value.

  Flag Value

   Description

0

 It is the default value
and performs the non case sensitive search

1

 It performs the case sensitive property search

2

 It returns the property value as it is set in the script or html code
Description of code :
To illustrate removeAttribute() method we have created a HTML page into which we have created a text box and a button. We have first set the read only property of text box to be true. When user clicks on the button "Remove readonly attribute of TextBox" it calls the function defined in the JavaScript named removeAlignment().

function removeAlignment(){
    var read = document.getElementById("txt")
        .removeAttribute("readonly",0);
    alert("textbox readonly attribute removed");
  }
Above lines of code describes the functionality of function removeAlignment(). It first takes the element object by using method document.getElementById(), thereafter we can apply removeAttribute() method. Here is the full example code as follows :

<html>
<body>
<script language="JavaScript">
  function removeAlignment(){
    var read=document.getElementById("txt")
        .removeAttribute("readonly",0);
 alert("textbox readonly attribute removed");
  }
</script>
<div style="background: #cf2255; width:'100%';" 
   align="center">
  <font color="#05ff20" size="12pt">
  <b>Remove Attribute Example</b>
  </font>
</div>
<center>
 <div id="divId" align="center" style="background: #ffffcc;
          width:'100%';">
 <input id="txt" type="text" readonly="true" />
    <p>Insert some text into text box</p>
      <input type="button" value="Remove readonly attribute 
    of TextBox" onclick="removeAlignment();">
  </div>
</center>
</body>
</html>
Output :
When you try to input some text into the text box, it doesn't allow you to input since it has read only attribute set to be true.

Click on the button "Remove readonly attribute of TextBox" to remove attribute "readonly" for the input text box.

Once the attribute "readonly" is removed we can insert text into text box.

The most famous and best-selling Denman hairbrushes in the world

| 18 thg 1, 2010


PR shots for Website 009 - small

All of the Denman classic styling brushes are characterised by smooth, firm nylon bristles embedded in a pure rubber base. The nylon bristles are rounded at the ends, so they do not scratch the hair or scalp. The rubber base is semi-circular in shape and this becomes more defined in the larger sizes. During blowdrying, you can rotate the brush through the ends of the hair, adding slight curl and bend. The Denman classic styling brushes are particularly heat resistant, so they can be used with a hair dryer. They can also be easily cleaned using soap and water. 
The D14 small styling brush has only 5 rows of nylon bristles, making it the  perfect compact tool for shorter hair types, or for shaping fringes. Excellent handbag size for on-the-go styling!
The D3 medium styling brush has 7 rows of nylon bristles, and is recommended for medium to longer hair. It is Denman’s most popular styling brush!
Learn more about the most popular Denman classic styling brushes from:http://www.denmanbrush.com/acatalog/Classic_Styling.html 
|



Cách 1. Chép và dán:

Dán code được tạo ra từ quá trình khởi tạo quảng cáo trong tài khoản Google AdSense rồi chèn trực tiếp vào tiện ích HTML/JavaScript của Blogger.

Ưu điểm:

- Dễ thao tác.
- Quản lý được hiệu quả các kênh (channel).

Nhược điểm:

- Thêm mới hoặc thay đổi kích thước quảng cáo phải tạo lại quảng cáo khác.
- Không đặt được quảng cáo trong bài đăng.

Cách 2. Kết nối tài khoản AdSense vào Blogger:

Lần đầu sử dụng bạn phải kết nối tài khoản AdSense vào Blogger. Trên Bố cục, chọn Thêm tiện ích (Add a Gadget) | Adsense, khai báo địa chỉ email đã dùng đăng ký AdSense và mã bưu điện hoặc 5 số cuối của số điện thoại trong đơn đăng ký.

Sau khi khai báo xong, từ nay muốn cho quảng cáo hiển thị bạn chỉ việc nhấn chọn AdSense, kích thước, kiểu nội dung, màu sắc quảng cáo, và lưu lại rồi kéo thả vào vị trí khác.

Ưu:

- Dễ thao tác.
- Thêm mới, xóa hoặc thay đổi kích thước quảng cáo phải thao tác ngay trong Blogger.

Khuyết:

- Không quản lý được hiệu quả các kênh (channel).
- Không đặt được quảng cáo trong bài đăng.

Như vậy cả hai cách trên đều gặp hạn chế về vị trí quảng cáo, không thể đặt giữa các bài đăng hoặc bên trong bài đăng - nơi được xem có tỉ lệ click cao nhất. Và đó là lý đo để bạn tiếp tục đọc.

II. ĐẶT QUẢNG CÁO GIỮA CÁC BÀI ĐĂNG:

Đăng nhập Blogger, nhấn Chỉnh sửa (Edit) thành phần Blog Spots (Bài đăng) trên Bố cục (Layout). Cửa sổ để cấu hình bài đăng hiện ra, nhấn chuột chọn Hiển thị Quảng cáo giữa các bài đăng (Show Ads Between Posts), cấu hình quảng cáo rồi chọn lưu lại.

Quảng cáo sẽ xuất hiện nằm giữa các bài đăng. Nghĩa là sẽ có 1 quảng cáo đi kèm sau số lượng bài đăng do bạn chọn [Show after # every posts (up to 3 times on a page)][Hiển thị sau mỗi # bài đăng (tối đa 3 lần trên một trang)] giả sử bạn chưa sử dụng ở các vị trí khác. Lưu ý: Bạn phải kết nối tài khoản AdSense vào Blogger như trên vừa đề cập.

III. ĐẶT QUẢNG CÁO BÊN TRONG BÀI ĐĂNG:

Với cách này, bạn phải chèn code Google AdSense vào template của blog. Quảng cáo nên được bao bên trong ID, class hoặc kiểu CSS riêng tương ứng với các gợi ý:

Gợi ý 1:
<div class='ads'>
  Đoạn mã Google AdSense (+)
</div>

Gợi ý 2:
<div id='ads'>
  Đoạn mã Google AdSense
</div>

Khi đó chúng ta cần khai báo CSS tương ứng và đặt nó giữa <b:skin><![CDATA[/* và ]]></b:skin>trong template.
Dùng cho gợi ý 1:
#ads{
  float: left;
  margin: 5px 5px 5px 5px;
}

Dùng cho gợi ý 2:
.ads{
  float: left;
  margin: 5px 5px 5px 5px;
}

Gợi ý 3. Gom cả hai thành một:
<div style='float: left; margin: 5px 5px 5px 5px;'>
  Đoạn mã Google AdSense
</div>

Thuộc tính float sẽ làm vị trí của div hiển thị bên trái (left) hay bên phải (right) trong thành phần chứa nó. Giống thuộc tính text-align của văn bản hay align của hình ảnh. Nhưng ở đây div hiển thị như một chiếc hộp nằm bên trái hay phải của khung văn bản. Đương nhiên nếu bạn biết nhiều về CSS bạn có thể thêm, bớt, làm nổi bậc khung chứa quảng cáo này. Theo kinh nghiệm của nhiều người, cách đặt code này linh động và hiệu quả hơn cả, thích hợp các kích thước 336 x 280, 300 x 250, 250 x 250 và 200 x 200.

Trong trường hợp muốn quảng cáo chỉ xuất hiện khi xem bài đăng cụ thể, div trên phải đặt bên trong:
<b:if cond='data:blog.pageType == "item"'>
      Đặt div mà bạn dùng vào đây 
     </b:if>

Đoạn mã Google AdSense để dùng:

a. Lấy từ tài khoản AdSense:

Đăng nhập tài khoản AdSense, tạo code quảng cáo mới và chuyển đổi các ký tự đặc biệt như < và > sang HTML. Bạn có thể tham khảo công cụ chuyển đổi ở hướng dẫn về cách đặt code của chodientu.vn. Việc chuyển đổi này không vi phạm quy định của Google AdSense.

b. Lấy từ template Blogger:

Bảo đảm rằng bạn đang dùng hướng dẫn phần II. Đăng nhập Blogger, chọn Bố cục (Layout) | đánh dấu Mở rộng tiện ích mẫu (Expand Widget Templates) để tìm đoạn code bên dưới và thêm vào các ký tự có màu nổi bật:
<data:adStart/>
    <b:loop values='data:posts' var='post'>
      <b:if cond='data:post.dateHeader'>
        <h2 class='date-header'><data:post.dateHeader/></h2>
      </b:if>
      <b:include data='post' name='post'/>
      <b:if cond='data:blog.pageType == &quot;item&quot;'>
        <b:include data='post' name='comments'/>
      </b:if>
     <!--
      <b:if cond='data:post.includeAd'>
        <data:adEnd/>
        <data:adCode/>
        <data:adStart/>
      </b:if>
     -->
    </b:loop>
    <data:adEnd/>

Việc thêm các ký tự này nhằm vô hiệu đoạn mã hiển thị quảng cáo nằm giữa các bài đăng. Và đây chính là đoạn code Google AdSense chúng ta cần:
<b:if cond='data:post.includeAd'>
        <data:adEnd/>
        <data:adCode/>
        <data:adStart/>
      </b:if> 

Với cách lấy code thế này, bạn không phải chạm đến code AdSense gốc.

Và chúng ta sẽ chèn vào template:

<div class='post-body entry-content'>
    Đặt code vào đây, quảng cáo sẽ xuất hiện dưới tiêu đề bài đăng
      <data:post.body/>
      <div style='clear: both;'/> <!-- clear for photos floats -->
    </div>

    <div class='post-footer'>
    Đặt code vào đây, quảng cáo sẽ xuất hiện dưới chân bài đăng
    <div class='post-footer-line post-footer-line-1'>
      <span class='post-author vcard'>
        <b:if cond='data:top.showAuthor'>
          <data:top.authorLabel/>
          <span class='fn'><data:post.author/></span>
        </b:if>
      </span>

Hay nhiều vị trí khác nữa tùy thuộc vào template. Chúc vui vẻ!
Theo Thuthuatblog

April 2009 calendar wallpaper Photoshop tutorial

|
April 2009 calendar wallpaper Photoshop tutorial
Making a cool and colorful April 2009 calendar wallpaper.

Begin your work by creating a new file (File>New) of 1280×1024 px and 72 dpi.

Using the Rectangle Tool (U) now, it’s possible to represent the background of the calendar we want to have in the end.

Making a cool and colorful April 2009 calendar wallpaper in Photoshop CS4

JSP Interview Questions

| 16 thg 1, 2010



JSP Interview Questions


Question:What is a output comment? 
Question:What is a Hidden comment?  
Question:What is an Expression?
Question:What is a Declaration ?  
Question:What is a Scriptlet?
Question:What are implicit objects? List them?
Question:Difference between forward and sendRedirect?
Question:What are the different scope values for the ?
Question:Explain the life-cycle methods in JSP?

Q:What is a output comment?
A:A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.
JSP Syntax


Example 1



Displays in the page source:
 

Q:What is a Hidden Comment?
A:A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>. 
JSP Syntax

Examples







 

Q:What is a Expression?
A:An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like


You cannot use a semicolon to end an expression
 

Q:What is a Declaration?
A:A declaration 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 they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.




 

Q:What is a Scriptlet?
A:A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can1.Declare variables or methods to use later in the file (see also Declaration).

2.Write expressions valid in the page scripting language (see also Expression).

3.Use any of the JSP implicit objects or any object declared with a tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.

Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.
 

Q:What are implicit objects? List them?
A:Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below
  • request
  • response
  • pageContext
  • session
  • application
  • out
  • config
  • page
  • exception
 

Q:Difference between forward and sendRedirect?
A:When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
 

Q:What are the different scope valiues for the ?
A:The different scope values for are
1. page
2. request
3.session
4.application

 

Q:Explain the life-cycle mehtods in JSP?
A:THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method_jspService().
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.

JSP – INTERVIEW QUESTION

1. What is JSP? Describe its concept.  JSP is a technology that combines HTML/XML markup languages and elements of Java programming Language to return dynamic content to the Web client, It is normally used to handle Presentation logic of a web application, although it may have business logic.
2. What are the lifecycle phases of a JSP? JSP page looks like a HTML page but is a servlet. When presented with JSP page the JSP engine does the following 7 phases.
1. Page translation: -page is parsed, and a java file which is a servlet is created.
2. Page compilation: page is compiled into a class file
3. Page loading : This class file is loaded.
4. Create an instance :- Instance of servlet is created
5. jspInit() method is called
6. _jspService is called to handle service calls
7. _jspDestroy is called to destroy it when the servlet is not required.
3. What is a translation unit? JSP page can include the contents of other HTML pages or other JSP files. This is done by using the include directive. When the JSP engine is presented with such a JSP page it is converted to one servlet class and this is called a translation unit, Things to remember in a translation unit is that page directives affect the whole unit, one variable declaration cannot occur in the same unit more than once, the standard action jsp:useBean cannot declare the same bean twice in one unit.
4. How is JSP used in the MVC model? JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client.
5. 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 and not specific to any servlet or JSP.
6. What is a output comment? A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as un-interpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser
7. What is a Hidden Comment? A comment that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or “comment out” part of your JSP page.
8. What is a Expression? Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed.
9. 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.
10. What is a Scriptlet? A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables or methods 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 .
11. What are the implicit objects? List them.  Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects are: request response pageContext session application out config page exception
12. What’s the difference between forward and sendRedirect? When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely within the web container And then returns to the calling method. When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
__________________

Generics in Java – Part I

|

Abstract

Java 5 (JDK 1.5) introduced the concept of Generics or parameterized types. In this article, I introduce the concepts of Generics and show you examples of how to use it. In Part II, we will look at how Generics are actually implemented in Java and some issues with the use of Generics.

Issue of Type-Safety

Java is a strongly typed language. When programming with Java, at compile time, you expect to know if you pass a wrong type of parameter to a method. For instance, if you define:
 Collapse
Dog aDog = aBookReference; // ERROR
where, aBookReference is a reference of type Book, which is not related to Dog, you would get a compilation error.
Unfortunately though, when Java was introduced, this was not carried through fully into the Collections library. So, for instance, you can write:
 Collapse
Vector vec = new Vector();
vec.add("hello");
vec.add(new Dog());
…
There is no control on what type of object you place into the Vector. Consider the following example:
 Collapse
package com.agiledeveloper;

import java.util.ArrayList;
import java.util.Iterator;

public class Test
{
    public static void main(String[] args)
    {
        ArrayList list = new ArrayList();
        populateNumbers(list);

        int total = 0;
        Iterator iter = list.iterator();
        while(iter.hasNext())
        {
            total += ((Integer) (iter.next())).intValue();
        }

        System.out.println(total);
    }

    private static void populateNumbers(ArrayList list)
    {
        list.add(new Integer(1));
        list.add(new Integer(2));
    }
}
In the above program, I create an ArrayList, populate it with some Integer values, and then total the values by extracting the Integers out of the ArrayList.
The output from the above program is a value of 3, as you would expect.
Now, what if I change the populateNumbers() method as follows:
 Collapse
private static void populateNumbers(ArrayList list)
{
    list.add(new Integer(1));
    list.add(new Integer(2));
    list.add("hello");
}
I will not get any compilation errors. However, the program will not execute correctly. We will get the following runtime error:
 Collapse
Exception in thread "main" java.lang.ClassCastException: 
  java.lang.String at com.agiledeveloper.Test.main(Test.java:17)…
We did not quite have this type-safety with collections pre-Java-5.

What are Generics?

Back in the good old days when I used to program in C++, I enjoyed using a cool feature in C++ – templates. Templates give you type-safety while allowing you to write code that is general, that is, it is not specific to any particular type. While C++ templates is a very powerful concept, there are a few disadvantages with it. First, not all compilers support it well. Second, it is fairly complex that it takes quite an effort to get good at using it. Lastly, there are a number of idiosyncrasies in how you can use it that it starts hurting the head when you get fancy with it (this can be said generally about C++, but that is another story). When Java came out, most features in C++ that were complex, like templates and operator overloading, were avoided.
In Java 5, finally, it was decided to introduce Generics. Though Generics – the ability to write general or generic code which is independent of a particular type – is similar to templates in C++ in concept, there are a number of differences. For one, unlike C++ where different classes are generated for each parameterized type, in Java, there is only one class for each generic type, irrespective of how many different types you instantiated it with. There are, of course, certain problems as well in Java Generics, but that we will talk about in Part II. In this part I, we will focus on the good things.
The work of Generics in Java originated from a project called GJ1 (Generic Java) which started out as a language extension. This idea then went through the Java Community Process (JCP) as a Java Specification Request (JSR) 142.

Generic Type-Safety

Let’s start with a non-generic example we looked at to see how we can benefit from Generics. Let’s convert the code above to use Generics. The modified code is shown below:
 Collapse
package com.agiledeveloper;

import java.util.ArrayList;
import java.util.Iterator;

public class Test
{
    public static void main(String[] args)
    {
        ArrayList list = new ArrayList();
        populateNumbers(list);

        int total = 0;
        for(Integer val : list)
        {
           total = total + val;
        }

        System.out.println(total);
    }

    private static void populateNumbers(ArrayList list)
    {
        list.add(new Integer(1));
        list.add(new Integer(2));
        list.add("hello");
    }
}
I am using ArrayList<Integer> instead of the ArrayList. Now, if I compile the code, I get a compilation error:
 Collapse
Test.java:26: cannot find symbol
symbol  : method add(java.lang.String)
location: class java.util.ArrayList
        list.add("hello");
            ^
1 error
The parameterized type of ArrayList provides the type-safety. “Making Java easier to type and easier to type,” was the slogan of the Generics contributors in Java.

Naming Conventions

In order to avoid confusion between the generic parameters and the real types in your code, you must follow a good naming convention. If you are following good Java conventions and software development practices, you would probably not be naming your classes with single letters. You would also be using mixed case with class names, starting with upper case. Here are some conventions to use for Generics:
  • Use the letter E for collection elements, like in the definition:
  •  Collapse
    public class PriorityQueue {…}
  • Use letters T, U, S, etc. for general types.

Writing Generic Classes

The syntax for writing a generic class is pretty simple. Here is an example of a generic class:
 Collapse
package com.agiledeveloper;

public class Pair
{
    private E obj1;
    private E obj2;
    
    public Pair(E element1, E element2)
    {
        obj1 = element1;
        obj2 = element2;
    }
    
    public E getFirstObject() { return obj1; }
    public E getSecondObject() { return obj2; }
}
This class represents a pair of values of some generic type E. Let’s look at some examples of usage of this class:
 Collapse
// Good usage
Pair aPair = new Pair(new Double(1), new Double(2.2));
If we try to create an object with types that mismatch, we will get a compilation error. For instance, consider the following example:
 Collapse
// Wrong usage
Pair anotherPair = new Pair(new Integer(1), new Double(2.2));
Here, I am trying to send an instance of Integer and an instance of Double to an instance of Pair. However, this will result in a compilation error.

Generics and Substitutability

Generics honors the Liskov’s Substitutability Principle4. Let me explain that with an example. Say, I have a Basket of Fruits. To it I can add Oranges, Bananas, Grapes, etc. Now, let’s create a Basket of Banana. To this, I should only be able to add Bananas. It should disallow adding other types of fruits. Banana is a Fruit, i.e., Banana inherits from Fruit. Should Basket of Banana inherit from Basket for Fruits, as shown in the figure below?

If Basket of Banana were to inherit from Basket of Fruit, then you may get a reference of type Basket of Fruit to refer to an instance of Basket of Banana. Then, using this reference, you may add a Banana to the basket, but you may also add an Orange. While adding a Banana to a Basket of Banana is OK, adding an Orange is not. At best, this will result in a runtime exception. However, the code that uses Basket of Fruits may not know how to handle this. The Basket of Banana is not substitutable where a Basket of Fruits is used.
Generics honors this principle. Let’s look at this example:
 Collapse
Pair objectPair = new Pair(new Integer(1), new Integer(2));
This code will produce a compile time error:
 Collapse
Error:  line (9) incompatible types found   :
com.agiledeveloper.Pair required: 
    com.agiledeveloper.Pair
Now, what if you want to treat different type of Pairs commonly as one type? We will look at this later in the Wildcardsection.
Before we leave this topic, let’s look at one weird behavior though. While:
 Collapse
Pair objectPair = new Pair(new Integer(1), new Integer(2));
is not allowed, the following is allowed, however:
 Collapse
Pair objectPair = new Pair(new Integer(1), new Integer(2));
The Pair without any parameterized type is the non-generic form of the Pair class. Each generic class also has a non-generic form so it can be accessed from a non-generic code. This allows for backward compatibility with existing code or code that has not been ported to use Generics. While this compatibility has a certain advantage, this feature can lead to some confusion and also type-safety issues.

Generic Methods

In addition to classes, methods may also be parameterized.
Consider the following example:
 Collapse
public static  void filter(Collection in, Collection out)
{
    boolean flag = true;
    for(T obj : in)
    {
        if(flag)
        {
            out.add(obj);
        }
        flag = !flag;
    }
}
The filter() method copies alternate elements from the in collection to the out collection. The <T> in front of thevoid indicates that the method is a generic method with <T> being the parameterized type. Let’s look at a usage of this generic method:
 Collapse
ArrayList lst1 = new ArrayList();
lst1.add(1);
lst1.add(2);
lst1.add(3);

ArrayList lst2 = new ArrayList();
filter(lst1, lst2);
System.out.println(lst2.size());
We populate an ArrayList lst1 with three values and then filter (copy) its contents into another ArrayList lst2. The size of lst2 after the call to the filter() method is 2.
Now, let’s look at a slightly different call:
 Collapse
ArrayList dblLst = new ArrayList();
filter(lst1, dblLst);
Here I get a compilation error:
 Collapse
Error:  
line (34) filter(java.util.Collection,java.util.Collection) 
in com.agiledeveloper.Test cannot be applied to
(java.util.ArrayList,
java.util.ArrayList)
The error says that it can’t send an ArrayList of different types to this method. This is good. However, let’s try the following:
 Collapse
ArrayList lst3 = new ArrayList();
ArrayList lst = new ArrayList();
lst.add("hello");
filter(lst, lst3);
System.out.println(lst3.size());
Like it or not, this code compiles with no error, and the call to lst3.size() returns a 1. First, why did this compile and what’s going on here? The compiler bends over its back to accommodate calls to generic methods, if possible. In this case, by treating lst3 as a simple ArrayList, without any parameterized type that is (refer to the last paragraph in the “Generics and Substitutability” section above), it is able to call the filter method.
Now, this can lead to some problems. Let’s add another statement to the example above. As I start typing, the IDE (I am using IntelliJ IDEA) is helping me with code prompt as shown below:

It says that the call to the get() method takes an index and returns an Integer. Here is the completed code:
 Collapse
ArrayList lst3 = new ArrayList();
ArrayList lst = new ArrayList();
lst.add("hello");
filter(lst, lst3);
System.out.println(lst3.size());
System.out.println(lst3.get(0));
So, what do you think should happen when you run this code? May be runtime exception? Well, surprise! We get the following output for this code segment:
 Collapse
1
hello
Why is that? The answer is in what actually gets compiled (we will discuss more about this in Part II of this article). The short answer for now is, even though code completion suggested that an Integer is being returned, in reality, the return type is Object. So, the string "hello" managed to get through without any error.
Now, what happens if we add the following code:
 Collapse
for(Integer val: lst3)
{
    System.out.println(val);
}
Here, clearly, I am asking for an Integer from the collection. This code will raise a ClassCastException. While Generics is supposed to make our code type-safe, this example shows how we can easily, with intent or by mistake, bypass that, and at best, end up with runtime exception, or at worst, have the code silently misbehave. Enough of those issues for now. We will look at some of these gotchas further in Part II. Let’s progress further on what works well for now, in this Part I.

Upper Bounds

Let’s say we want to write a simple generic method to determine the maximum of two parameters. The method prototype would look like this:
 Collapse
public static  T max(T obj1, T obj2)
I would use it as shown below:
 Collapse
System.out.println(max(new Integer(1), new Integer(2)));
Now, the question is how do I complete the implementation of the max() method? Let’s take a stab at this:
 Collapse
public static  T max(T obj1, T obj2)
{
    if (obj1 > obj2) // ERROR
    {
        return obj1;
    }
    return obj2;
}
This will not work. The > operator is not defined on references. Hmm, how can I then compare the two objects? TheComparable interface comes to mind. So, why not use the comparable interface to get our work done:
 Collapse
public static  T max(T obj1, T obj2)
{
    // Not elegant code
    Comparable c1 = (Comparable) obj1;
    Comparable c2 = (Comparable) obj2;

    if (c1.compareTo(c2) > 0)
    {
        return obj1;
    }
    return obj2;
}
While this code may work, there are two problems. First, it is ugly. Second, we have to consider the case where the cast to Comparable fails. Since we are so heavily dependent on the type implementing this interface, why not ask the compiler to enforce this? That is exactly what upper bounds does for us. Here is the code:
 Collapse
public static extends Comparable> T max(T obj1, T obj2)
{
    if (obj1.compareTo(obj2) > 0)
    {
        return obj1;
    }
    return obj2;
}
The compiler will check to make sure that the parameterized type given when calling this method implements theComparable interface. If you try to call max() with instances of some type that does not implement the Comparableinterface, you will get a stern compilation error.

Wildcard

We are progressing well so far, and you are probably eager to dive into a few more interesting concepts with Generics. Let’s consider this example:
 Collapse
public abstract class Animal
{
    public void playWith(Collection playGroup)
    {

    }
}

public class Dog extends Animal
{
    public void playWith(Collection playGroup)
    {
    }
}
The Animal class has a playWith() method that accepts a Collection of Animals. The Dog, which extendsAnimal, overrides this method. Let’s try to use the Dog class in an example:
 Collapse
Collection dogs = new ArrayList();
        
Dog aDog = new Dog();
aDog.playWith(dogs); //ERROR
Here, I create an instance of Dog and send a Collection of Dogs to its playWith() method. We get a compilation error:
 Collapse
Error:  line (29) cannot find symbol 
method playWith(java.util.Collection)
This is because a Collection of Dogs can’t be treated as a Collection of Animals which the playWith()method expects (see the section “Generics and Substitutability” above). However, it would make sense to be able to send a Collection of Dogs to this method, isn’t it? How can we do that? This is where the wildcard or unknown type comes in.
We modify both the playMethod() methods (in Animal and Dog) as follows:
 Collapse
public void playWith(Collection playGroup)
The Collection is not of type Animal. Instead it is of unknown type (?). Unknown type is not Object, it is just unknown or unspecified.
Now, the code:
 Collapse
aDog.playWith(dogs);
compiles with no error.
There is a problem however. We can also write:
 Collapse
ArrayList numbers = new ArrayList();
aDog.playWith(numbers);
The change I made to allow a Collection of Dogs to be sent to the playWith() method now permits aCollection of Integers to be sent as well. If we allow that, that will become one weird dog. How can we say that the compiler should allow Collections of Animals or Collections of any type that extends Animal, but not anyCollection of other types? This is made possible by the use of upper bounds as shown below:
 Collapse
public void playWith(Collectionextends Animal> playGroup)
One restriction of using wildcards is that you are allowed to get elements from a Collection<?>, but you can’t add elements to such a collection – the compiler has no idea what type it is dealing with.

Lower Bounds

Let’s consider one final example. Assume we want to copy elements from one collection to another. Here is my first attempt for a code to do that:
 Collapse
public static  void copy(Collection from, Collection to) {…}
Let’s try using this method:
 Collapse
ArrayList dogList1 = new ArrayList();
ArrayList dogList2 = new ArrayList();
//
copy(dogList1, dogList2);
In this code, we are copying Dogs from one Dog ArrayList to another.
Since Dogs are Animals, a Dog may be in both a Dog’s ArrayList and an Animal’s ArrayList, isn’t it? So, here is the code to copy from a Dog’s ArrayList to an Animal’s ArrayList.
 Collapse
ArrayList animalList = new ArrayList();
copy(dogList1,  animalList);
This code, however, fails compilation with error:
 Collapse
Error:  
line (36) copy(java.util.Collection,java.util.Collection) 
in com.agiledeveloper.Test cannot be applied 
to (java.util.ArrayList,
java.util.ArrayList)
How can we make this work? This is where the lower bounds come in. Our intent for the second argument of Copy is for it to be of either type T or any type that is a base type of T. Here is the code:
 Collapse
public static  void copy(Collection from, Collectionsuper T> to)
Here we are saying that the type accepted by the second collection is the same type as T is, or its super type.

Where are We?

I have shown, using examples, the power of the Generics in Java. There are issues with using Generics in Java, however. I will defer discussions on this to the Part II of this article. In Part II, we will discuss some restrictions of Generics, how Generics are implemented in Java, the effect of type erasure, changes to the Java class library to accommodate Generics, issues with converting a non-Generics code to Generics code, and finally, some of the pitfalls or drawbacks of Generics.

Conclusion

In this Part I we discussed about Generics in Java and how we can use it. Generics provide type-safety. Generics are implemented in such a way that it provides backward compatibility with non-generic code. These are simpler than templates in C++ and also there is no code bloat when you compile. In Part II we discuss the issues with using Generics.

References

  1. GJ - A Generic Java Language Extension
  2. JSR 14
  3. Java SE Downloads - Previous Release - J2SE 5.0
  4. Oo Design Principles