Ebeworld’s Weblog

Trying to create

Benefit of using Swing over AWT

What is the difference between AWT and Swing? LF DC

 Swing provides a richer set of components than AWT. They are 100% Java-based. There are a few other advantages to Swing over AWT:

• Swing provides both additional components like JTable, JTree etc and added functionality to AWT-replacement components.

• Swing components can change their appearance based on the current “look and feel” library that’s being used.

• Swing components follow the Model-View-Controller (MVC) paradigm, and thus can provide a much more

flexible UI.

• Swing provides “extras” for components, such as: icons on many components, decorative borders for

components, tool tips for components etc.

• Swing components are lightweight (less resource intensive than AWT).

Swing provides built-in double buffering (which means an off-screen buffer [image] is used during drawing

and then the resulting bits are copied onto the screen. The resulting image is smoother, less flicker and quicker than drawing directly on the screen).

• Swing provides paint debugging support for when you build your own component i.e.-slow motion rendering.

Swing also has a few disadvantages:

• If you’re not very careful when programming, it can be slower than AWT (all components are drawn).

• Swing components that look like native components might not behave exactly like native components.

October 14, 2008 Posted by ebeworld | Java, TopCoder | , | No Comments Yet

Swing Layouts

Explain layout managers?

Layout managers are used for arranging GUI components in windows. The standard layout managers are:

• FlowLayout: Default layout for Applet and Panel. Lays out components from left to right, starting new rows if necessary.

• BorderLayout: Default layout for Frame and Dialog. Lays out components in north, south, east, west and

center. All extra space is placed on the center.

• CardLayout: stack of same size components arranged inside each other. Only one is visible at any time. Used in TABs.

• GridLayout: Makes a bunch of components equal in size and displays them in the requested number of rows

and columns.

• GridBagLayout: Most complicated but the most flexible. It aligns components by placing them within a grid of cells, allowing some components to span more than one cell. The rows in the grid aren’t necessarily all the same height, similarly, grid columns can have different widths as well.

BoxLayout: is a full-featured version of FlowLayout. It stacks the components on top of each other or places  them in a row.

October 14, 2008 Posted by ebeworld | Interview Questions, Java | , | No Comments Yet

Applet event sequence

What is the order of method invocation in an applet? LF

The Applet’s life cycle methods are as follows:

• public void init() : Initialization method called only once by the browser.

• public void start() : Method called after init() and contains code to start processing. If the user leaves the

page and returns without killing the current browser session, the start () method is called without being

preceded by init ().

• public void stop() : Stops all processing started by start (). Done if user moves off page.

• public void destroy() : Called if current browser session is being terminated. Frees all resources used by the

applet.

October 14, 2008 Posted by ebeworld | Interview Questions, Java | , | No Comments Yet

pku 3589

Number-guessing Game
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 1499   Accepted: 1106

Description

Larry likes playing the number-guessing game.

Two players are needed in a game. Suppose they are X and Y, and X presents a number for Y to guess. Firstly, X chooses a number with four different digits, keeping it in mind, and tells Y to start guessing. Every time Y has guessed, X should give out *A*B to show Y how close to the number his answer is. Here the symbol * stands for a number, and the number before A is the number of digits in Y’s answer with both correct value and position. The number before B is the number of digits in Y’s answer with correct value but incorrect position.

For example, if X chooses the number 5204, and Y guesses 4902, then X should give out 1A2B, in which 1A corresponds for digit 0 with both correct value and position and 2B corresponds for digit 2 and 4 with correct value but incorrect position. Then Y will go on guessing according to 1A2B that X presents him until he gets the totally correct number 5204 (when X shows him 4A0B).

Now you are given two numbers, and what you need to do is just testing how close they are.

Input

The first line of the input is an integer T which indicates the number of test cases. For each test case, input two numbers. Each number contains four different digits.

Output

For each test case, output *A*B stands for how close the two numbers are.
 

Sample Input

2
5204 4902
0123 3210

Sample Output

1A2B
0A4B

Source

#include<iostream>
using namespace std;
int main(){ 
char a[5],b[5]; 
int n,i,j; 
cin>>n; 
while(n) {
  cin>>a>>b;
  int x=0,y=0; 
    for( i = 0; i< 4; i++)
   for( j = 0 ; j < 4; j++)   {
    if(a[i]==b[i])
     x++;
    if(i!=j)
     if(a[i]==b[j])     {
      y++;
     break;
     }
       } 
cout<<x/4<<”A”<<y<<”B”<<endl;
  n–; 
return 0;
}

October 14, 2008 Posted by ebeworld | Algorithms | , , | No Comments Yet

Socket for interprocess communication

Sockets are communication channels, which facilitate inter-process communication. Never thought in this way, i always thought socket is for network related stuffs only.

October 14, 2008 Posted by ebeworld | Interview Questions, Java | , | No Comments Yet

Java Synchronized collection

Returns a synchronized (thread-safe) collection backed by the specified collection. In order to guarantee serial access, it is critical that all access to the backing collection is accomplished through the returned collection.It is imperative that the user manually synchronize on the returned collection when iterating over it:

  Collection c = Collections.synchronizedCollection(myCollection);
     ...
  synchronized(c) {
      Iterator i = c.iterator(); // Must be in the synchronized block
      while (i.hasNext())
         foo(i.next());
  }

October 14, 2008 Posted by ebeworld | Interview Questions, Java | | No Comments Yet

Java checked and unchecked exceptions

exceptFig4

October 14, 2008 Posted by ebeworld | Interview Questions, Java | | No Comments Yet

Java Reference Types

  1. The JVM holds onto regular Objects until they are no longer reachable by either clients or any container. In other words Objects are garbage collected when there are no more live references to them. Dead references don’t count.
  2. Soft references can be deleted from a container if the clients are no longer referencing them and memory is tight.
  3. Weak references are automatically deleted from a container as soon clients stop referencing them.
  4. Phantom references point to objects that are already dead and have been finalised.

 

 

 

Soft vs Weak vs Phantom References
Type Purpose Use When GCed Implementing Class
Strong Reference An ordinary reference. Keeps objects alive as long as they are referenced. normal reference. Any object not pointed to can be reclaimed. default
Soft Reference Keeps objects alive provided there’s enough memory. to keep objects alive even after clients have removed their references (memory-sensitive caches), in case clients start asking for them again by key. After a first gc pass, the JVM decides it still needs to reclaim more space. java.lang.ref.SoftReference
Weak Reference Keeps objects alive only while they’re in use (reachable) by clients. Containers that automatically delete objects no longer in use. After gc determines the object is only weakly reachable java.lang.ref.WeakReference
java.util.WeakHashMap
Phantom Reference Lets you clean up after finalization but before the space is reclaimed (replaces or augments the use of finalize()) Special clean up processing After finalization. java.lang.ref.PhantomReference

October 13, 2008 Posted by ebeworld | Interview Questions, Java | , | No Comments Yet

TopCoder 250 point problem

Problem Statement

     Pig Latin is a simple way of encoding words. We have invented a competitor called “Vowel Latin”. It just changes the order of the letters in a word by moving all the vowels to the end, keeping them in the same order as they appeared in the original word.Vowels are defined to be the letters ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’ (in either uppercase or lowercase). The reordering of the letters in a word does not change their case. So the Vowel Latin version of “AmplifierX” would be “mplfrXAiie” 

Create a class VowelLatin that contains a method translate that is given a String word and that returns the Vowel Latin version of word.

Definition

    
Class: VowelLatin
Method: translate
Parameters: String
Returns: String
Method signature: String translate(String word)
(be sure your method is public)
    
 

Constraints

- word contains between 1 and 50 characters, inclusive.
- Each character in word is a letter (‘A’-'Z’, ‘a’-'z’).

Examples

0)  
    
"XYz"
Returns: "XYz"
The word contains no vowels so it is unchanged by translating to Vowel Latin.
1)  
    
"application"
Returns: "pplctnaiaio"
The 5 vowels in this word are all moved to the end of the word.
2)  
    
"qwcvb"
Returns: "qwcvb"
 
3)  
    
"aeioOa"
Returns: "aeioOa"
 

import java.util.*;

 

public class VowelLatin {

public String translate(String word){

char[] chars=word.toCharArray();

String vowels=”aeiouAEIOU”;

StringBuilder end=new StringBuilder();

StringBuilder beg=new StringBuilder();

for(char c:chars){

if(vowels.indexOf(c)>-1){

end.append(c);

}else{

beg.append(c);

}

}

beg.append(end.toString());

return beg.toString();

}

}

October 13, 2008 Posted by ebeworld | TopCoder | | No Comments Yet

TopCoder 500 point problem

Problem Statement

I want a list of BioServices that are associated with each KindOfInput (such as “gene”, “DNAFragment”, “genome”, etc.). What is available from my service provider is a list of strings, each containing the name of a service followed by all the KindsOfInput it requires.
Given a String[] services, return a String[] in which each element contains a KindOfInput followed by the names of all the services that use that kind of input.
Each KindOfInput should appear exactly once in the return. Within each element of the return, the service names should be in alphabetical order, and should be separated by the 2 characters “, ” (comma space). The KindOfInput should be separated from the first service name by the 5 characters ” ==> ” (space eq eq gt space). The returned list should be in alphabetical order.
Note that all names are case-sensitive, and that “alphabetical order” refers to the ASCII ordering, where, for example, ‘Z’ precedes ‘a’.
Definition

Class:
ServiceNames
Method:
makeList
Parameters:
String[]
Returns:
String[]
Method signature:
String[] makeList(String[] services)
(be sure your method is public)

Constraints
-
services will contain between 1 and 50 elements, inclusive.
-
Each element of services will contain between 1 and 50 characters, inclusive.
-
Each element of services will contain tokens separated by a single space (‘ ‘).
-
Each token will consist of 1 or more letters (‘A’-'Z’ or ‘a’-'z’).
-
The first tokens of the elements in services will be distinct.
-
Within each element of services the KindsOfInput will be distinct.
Examples
0)

{“BLAST Genome Annotation Sensitivity”,”PING”,”X Annotation”}
Returns: {“Annotation ==> BLAST, X”, “Genome ==> BLAST”, “Sensitivity ==> BLAST” }

1)

{“PING”}
Returns: { }
There are no KindsOfInput so the return has 0 elements.
2)

{“BLAST Genome annotation Sensitivity”,”PING”,”X Annotation”,”Apple X ample”}
Returns:
{“Annotation ==> X”,
“Genome ==> BLAST”,
“Sensitivity ==> BLAST”,
“X ==> Apple”,
“ample ==> Apple”,
“annotation ==> BLAST” }
annotation and Annotation are distinct kinds of input. annotation comes later alphabetically than any name that starts with an uppercase letter.

Solution:

import java.util.*;

public class ServiceNames {
public String[] makeList(String[] services){
HashMap<String,HashSet<String>> map=new HashMap<String,HashSet<String>>();
for(String service:services){
String[] comp=service.split(” “);
if(comp.length<2) continue;
HashSet<String> list=null;
for(int i=1;i<comp.length;i++){
if(!map.containsKey(comp[i])){
map.put(comp[i], new HashSet<String>());
}
list=map.get(comp[i]);
list.add(comp[0]);
}
}
ArrayList<String> ret=new ArrayList<String>();
StringBuilder result=new StringBuilder();
String[] keys=map.keySet().toArray(new String[0]);
for(String key:keys){
result=new StringBuilder(key+” ==> “);
HashSet<String> vals=map.get(key);
String[] svals=vals.toArray(new String[0]);
if(svals.length==0) continue;
Arrays.sort(svals);
result.append(svals[0]);
for(int i=1;i<svals.length;i++){
result.append(“, “+svals[i]);
}
ret.add(result.toString());
}
String[] sret=ret.toArray(new String[0]);
Arrays.sort(sret);
return sret;

}
}

October 13, 2008 Posted by ebeworld | TopCoder | | No Comments Yet