java4all@1986 java. Powered by Blogger.

Find maximum element of HashSet

>> Monday, May 23, 2011

import java.util.Collections;
import java.util.HashSet;

public class Main {

public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add(new Long("1111111111"));
hashSet.add(new Long("2222222222"));
hashSet.add(new Long("3333333333"));
hashSet.add(new Long("4444444444"));
hashSet.add(new Long("5555555555"));

Object obj = Collections.max(hashSet);
System.out.println(obj);
}
}

Read more...

An easy way to initialize a set without manually adding each element

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class MainClass {

public static void main(String[] a) {
String elements[] = { "A", "B", "C", "D", "E" };
Set set = new HashSet(Arrays.asList(elements));

System.out.println(set);

}

}

Read more...

Remove duplicate items from an ArrayList

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class Main {
public static void main(String[] argv) {
List arrayList1 = new ArrayList();

arrayList1.add("A");
arrayList1.add("A");
arrayList1.add("B");
arrayList1.add("B");
arrayList1.add("B");
arrayList1.add("C");

HashSet hashSet = new HashSet(arrayList1);

List arrayList2 = new ArrayList(hashSet);

for (Object item : arrayList2)
System.out.println(item);
}
}

Read more...

Convert a List (ArrayList) to an Array with zero length array

For this we use toArray() method.
import java.util.ArrayList;
import java.util.List;

public class Main {
public static void main(String[] args) {
List carList = new ArrayList();

carList.add("A");
carList.add("B");
carList.add("C");
carList.add("D");

String[] carArray = carList.toArray(new String[0]);

for (String car : carArray) {
System.out.println(car);
}
}
}


o/p:

/*
A
B
C
D
*/

Read more...

Adding Another Collection

For adding a collection we use addAll(collection) method.

import java.util.Vector;

public class MainClass {
public static void main(String args[]) {
Vector v = new Vector(5);
for (int i = 0; i < 10; i++) {
v.insertElementAt(i,0);
}
System.out.println(v);

Vector v2 = new Vector();
v2.addAll(v);
v2.addAll(v);

System.out.println(v2);
}
}

o/p:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Read more...

A boolean is being stored and then retrieved from an ArrayList

import java.util.ArrayList;

public class Main {
public static void main(String... args) {
ArrayList list = new ArrayList();
list.add(true);
boolean flag = list.get(0);
}
}

Read more...

Sorting arrays of objects

import java.util.Arrays;
public class MainClass {
public static void main(String args[]) throws Exception {
String[] a = new String[] { "A", "C", "B" };
Arrays.sort(a);
for (int i = 0, n = a.length; i < n; i++) {
System.out.println(a[i]);
}
}
}

Read more...

Sorting arrays.

For Sorting arrays we use Arrays,sort(array) method.
Example:

import java.util.Arrays;
public class MainClass {
public static void main(String[] a) {
int array[] = { 2, 5, -2, 6, -3 };
Arrays.sort(array);
for (int i : array) {
System.out.println(i);
}
}
}

Read more...

What is meant by singlepattern Design and example?

Singleton Pattern:

Singleton provides a global access point
A singleton often has the characteristics of a registry or lookup service.
A singleton prevents the client programmer from having any way to create an object except the ways you provide.
You must make all constructors private.
You must create at least one constructor to prevent the compiler from synthesizing a default constructor.
You provide access through public methods.
Making the class final prevents cloning.



Take a final class:

final class Singleton {
private static Singleton s = new Singleton(47);

private int i;

private Singleton(int x) {
i = x;
}

public static Singleton getReference() {
return s;
}

public int getValue() {
return i;
}

public void setValue(int x) {
i = x;
}
}
public class SingletonPattern {

public static void main(String[] args) {
Singleton s = Singleton.getReference();
String result = "" + s.getValue();
System.out.println(result);
Singleton s2 = Singleton.getReference();
s2.setValue(9);
result = "" + s.getValue();
System.out.println(result);
}
}

Read more...

Copy file and directory

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

//
FileUtils is a collection of routines for common file system operations.
public final class FileUtils {
public static final File CURRENT_DIR = new File(".");

/**
*
* Copies the first file or directory to the second file or directory.

*

* If the first parameter is a file and the second is a file, then the method
* copies the contents of the first file into the second. If the second file
* does not exist, it is created.

*

* If the first parameter is a file and the second is a directory, the file is
* copied to the directory, overwriting any existing copy.

*

* If the first parameter is a directory and the second is a directory, the
* first is copied underneath the second.

*

* If the first parameter is a directory and the second is a file name or does
* not exist, a directory with that name is created, and the contents of the
* first directory are copied there.
*
* @param source
* @param destination
*
* @throws IOException
*

    *
  • If the source does not exist.
  • *
  • If the user does not have permission to modify the
    * destination.
  • *
  • If the copy fails for some reason related to system I/O.
  • *

*
*/
public static void copy(File source, File destination) throws IOException {
if (source == null)
throw new NullPointerException("NullSource");

if (destination == null)
throw new NullPointerException("NullDestination");

if (source.isDirectory())
copyDirectory(source, destination);

else
copyFile(source, destination);
}

public static void copyDirectory(File source, File destination) throws IOException {
copyDirectory(source, destination, null);
}

public static void copyDirectory(File source, File destination, FileFilter filter)
throws IOException {
File nextDirectory = new File(destination, source.getName());

//
// create the directory if necessary...
//
if (!nextDirectory.exists() && !nextDirectory.mkdirs()) {
Object[] filler = { nextDirectory.getAbsolutePath() };
String message = "DirCopyFailed";
throw new IOException(message);
}

File[] files = source.listFiles();

//
// and then all the items below the directory...
//
for (int n = 0; n < files.length; ++n) {
if (filter == null || filter.accept(files[n])) {
if (files[n].isDirectory())
copyDirectory(files[n], nextDirectory, filter);

else
copyFile(files[n], nextDirectory);
}
}
}

public static void copyFile(File source, File destination) throws IOException {
//
// if the destination is a dir, what we really want to do is create
// a file with the same name in that dir
//
if (destination.isDirectory())
destination = new File(destination, source.getName());

FileInputStream input = new FileInputStream(source);
copyFile(input, destination);
}

public static void copyFile(InputStream input, File destination) throws IOException {
OutputStream output = null;

output = new FileOutputStream(destination);

byte[] buffer = new byte[1024];

int bytesRead = input.read(buffer);

while (bytesRead >= 0) {
output.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}

input.close();

output.close();
}

}

Read more...

Use FileWriter to write an array of strings to a file.

import java.io.FileWriter;

public class Main {
public static void main(String[] argv) throws Exception {
FileWriter fw = new FileWriter("file.dat");
String strs[] = { "com", "exe", "doc" };

for (int i = 0; i < strs.length; i++) {
fw.write(strs[i] + "\n");
}
fw.close();
}
}

Read more...

Important points in Exception Handling?

1.If we have try with multiple catch blocks ,the order of catch blocks must be from child to parent .
2.We can handle the Exceptions by using try and catch blocks.
3. Throws keyword can be used ,when the programmer doesn't want to handle the Exception and throws it out the method.
4.Throw keyword can be used , if the programmer want to handle an Exception Explicitly and throw in catch block.
5.try----> to maintain risky code.
6.catch---> to maintain Exception handling code.
7.finally------>to maintain clean code.
8.Throwable is the super class of all exceptions and errors.

Read more...

Difference Between Final,Finally and finalize()?

Final:
1.It is a modifier applicable for classes,methods and variables.
2.for the final classes we can't create child class that is inheritance is not possible.
3.Final methods can be overridden in child class.
4.for final variables re-assignment is not possible.

Finally:
1.It is a block associated with try,catch .
2.The main objective of finally block is to maintain clean-up code, which should be execute always.

Finalize:
1. It is a method ,should be execute by the garabage collector,just before destorying a object












Read more...

Method's to display error information

1.)printStackTrace: This error method display information as below
Name of Exception:Description
Stack trace

2.)toString():This error method display information as below
Name of Exception:Description

3.)getMessage:This error method display information as below
Description.

Read more...

Method's to display error information

1.printStackTrace:It display

Read more...

Exceptions

1.What is meant by Exception?
It is an unwanted or an unexpected event which disturbs normal flow of a program.

2.Difference Between Checked Exception And Unchecked Exception?
Checked Exception:The Exception which are checked by compiler at compilation time.
Unchecked Exception: The exception which are checked by JVM at Runtime.

3.ERRORS:There are unrecoverable,they due to system resources but not due to lack of program.

4.)Difference Between Partially checked and fully checked Exception?
An exception is said to be partially checked exception if some of it's child classes are checked.
An exception is said to be partially unchecked exception if and only if all it's child classes are checked.

Read more...

FaceBook Login

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

Total Pageviews

STATCOUNTER

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP