Using BitSet in Java 在Java中使用BitSet

Categories: Java; Tagged with: ; @ July 16th, 2012 21:50

This class implements a vector of bits that grows as needed. Each component of the bit set has a boolean value. The bits of a BitSet are indexed by nonnegative integers. Individual indexed bits can be examined, set, or cleared. One BitSet may be used to modify the contents of another BitSet through logical AND, logical inclusive OR, and logical exclusive OR operations.
By default, all bits in the set initially have the value false, for example:

BitSet bs = new BitSet(9); // Create a new bit set,the initial size is 9;
	bs.set(3); // set the value of index 3 to true;
	// bs.clear(3); // clear - set to false;
	bs.set(10);

	// the number of bits currently in this bit set, the last true index + 1;
	System.out.println(bs.size());
	// the bit length.
	System.out.println(bs.length());
	// the true index.
	System.out.println(bs.toString());

	// set to the complement of its current.
	bs.flip(3);

	System.out.println(bs.toString());

	// create a new bitset.
	BitSet bs3 = new BitSet();
	bs3.set(10); 
	System.out.println(bs.equals(bs3)); // true

	bs.clear(); // clear all
	bs.xor(bs3); // XOR
	System.out.println(bs);
}

Using Enum type in Java 在Java中使用泛型

Categories: Java; Tagged with: ; @ July 16th, 2012 21:05

Enum is a new feature shipped in Java 5, An enum type is a type whose fields consist of a fixed set of constants.

/**
 * Specify the currency type.
 * @author Guoliang
 */
public static enum  Currency{
	/** NICKLE */
	N("NICKLE", 0.05),
	/** DIME */
	D("DIME", 0.10),
	/** QUARTER */
	Q("QUARTER", 0.25),
	/** DOLLAR */
	DOLLAR("DOLLAR", 1.00);

	/** Abbr of the money type. */
	private String dispalyName;
	/** the value of the money. */
	private double value;

	// Constructor
	private Currency(String abbr, double value) {
		this.dispalyName = abbr;
		this.value = value;
	}

	public String getAbbr() {
		return dispalyName;
	}

	public double getValue() {
		return value;
	}

	public static void main(String[] args) {
		for (Currency currency : Currency.values()) {
			System.out.println(currency.getAbbr());
		}
	}

}

Java.lang.Enum is an abstract Class, so Enum can not extends other classes, btw, should not create enum instance, so the constructor need to be private: “only private is permitted.”

Ref: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

 

 

Singleton In JDK: java.lang.Runtime

Categories: Java; Tagged with: ; @ July 3rd, 2012 23:21

Some times we need write some Singleton class for some reasons, like we need a singleton to store application settings. btw, we need this singleton thread safe.

Here is a good example for open JDK:

/**
 * Every Java application has a single instance of class
 * Runtime that allows the application to interface with
 * the environment in which the application is running. The current
 * runtime can be obtained from the getRuntime method.
 * 

* An application cannot create its own instance of this class. * * @author unascribed * @see java.lang.Runtime#getRuntime() * @since JDK1.0 */ public class Runtime { private static Runtime currentRuntime = new Runtime(); /** * Returns the runtime object associated with the current Java application. * Most of the methods of class Runtime are instance * methods and must be invoked with respect to the current runtime object. * * @return the Runtime object associated with the current * Java application. */ public static Runtime getRuntime() { return currentRuntime; } /** Don't let anyone else instantiate this class */ private Runtime() {}

 

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/lang/Runtime.java

The private static runtime instance will initialized when the class loaded by JVM, so thread safe is guaranteed by JVM class load mechanism.

Using Session in Servlet/JSP

Categories: Java; Tagged with: ; @ July 3rd, 2012 0:03

Using session in Servlet:

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().write("Servlet HelloWorld!");
		
		HttpSession session = request.getSession(false);
		if(session == null) {
			response.sendRedirect("ServletLogin");
			return;
		}else {
			System.out.println(session.getId());
			Integer totalAccess = (Integer) session.getAttribute("totalAccess"); // Get session attribute;
			if(totalAccess == null) {
				totalAccess = 0;
			}
			
			totalAccess += 1;
			session.setAttribute("totalAccess", totalAccess); // set attribute
			
			response.getWriter().write("TotalAccess: " + session.getAttribute("totalAccess"));
		}

 

Using session in JSP:

Jsp page directive:

<%@ page
          [ language=”java” ]
          [ extends=”package.class” ]
          [ import=”{package.class | package.*}, …” ]
          [ session=”true | false” ]
          [ buffer=”none | 8kb | sizekb” ]
          [ autoFlush=”true | false” ]
          [ isThreadSafe=”true | false” ]
          [ info=”text” ]
          [ errorPage=”relativeURL” ]
          [ contentType=”mimeType [ ;charset=characterSet ]”   |   “text/html ; charset=ISO-8859-1” ]
          [ isErrorPage=”true | false” ]
%>

“session = true” by default.  when access “session”, if session is not existing, will create one by default.
we can set:

<%-- Prevent the creation of a session –%>
<%@ page session="false">

to prevent the Creation of a Session in a JSP Page.

 

We didn’t mention about the thread safe of session, here is a post from IBM DW:
http://www.ibm.com/developerworks/library/j-jtp09238/index.html

The difference between Forward and Redirect in Servlet

Categories: Java; Tagged with: ; @ July 1st, 2012 15:16

Redirect:

response.sendRedirect(“ServletLogin”); // User not login, redirect to the login page.

“redirect sets the response status to 302, and the new url in a Location header, and sends the response to the browser. Then the browser, according to the http specification, makes another request to the new url”

And you can forward to any URL.

image

Forward:

request.getServletContext().getRequestDispatcher(“/s/HelloWorld”).forward(request, response);

forward happens entirely on the server. The servlet container just forwards the same request to the target url, without the browser knowing about that. Hence you can use the same request attributes and the same request parameters when handling the new url. And the browser won’t know the url has changed (because it has happened entirely on the server)

So we can get the parameters in the target method:

request.getParameter(“userName”) // HelloWorld…doPost()..

Ref: http://stackoverflow.com/questions/6068891/difference-between-jsp-forward-and-redirect


this picture is from: http://lukejin.iteye.com/blog/586091

Newer Posts <-> Older Posts



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.