Thursday, June 25, 2009

How to Iterate a Set


Iterator it = set.iterator();
while (it.hasNext()) {
// Get the element
Object element = it.next();
}

How to Create a Set


Difference between List and Set : List can contain duplicate elements. Set can contain only unique elements. If you try to add the same element again then it will overwrite the new element on old one.

// Create the set
Set set = new HashSet();
// Add elements to the set
set.add("X");
set.add("Y");
set.add("Z");

// Adding an element that already exists in the set has no effect
set.add("X");
size = set.size(); // 3

// Remove elements from the set
set.remove("Z"); //set=["X","Y"]


// Determining if an element is in the set
boolean b = set.contains("A"); // true
b = set.contains("Z"); // false

How to Add and Remove One List from Another


// Create the lists
List samplelist1 = new ArrayList();
List samplelist2 = new ArrayList();

samplelist1.add("A");
samplelist2.add("B");

// Copy all the elements from samplelist2 to samplelist1 (samplelist1=samplelist1+samplelist2)
samplelist1.addAll(samplelist2); // samplelist1=["A","B"]

// Remove all the elements in samplelist1 from samplelist2 (samplelist1=samplelist1-samplelist2)
samplelist1.removeAll(samplelist2); // samplelist1=["A"]

How to Sort a List


// Create a list
String[] strArray = new String[] {"e", "a", "A"};
List list = Arrays.asList(strArray);

// Sort
Collections.sort(list); // A, a, e

Wednesday, June 24, 2009

How to Create an ArrayList


// Create the list
List list = new ArrayList();
// Append an element to the list
list.add("abc");
// Insert an element at the head of the list
list.add(0, "xyz");

How to Determine If the Current Thread Is Holding a Synchronized Lock


public synchronized void myMethod() {
boolean hasLock = false;
Object obj = new Object();

// Determine if current thread has lock for obj
hasLock = Thread.holdsLock(obj); // false
synchronized (obj) {
hasLock = Thread.holdsLock(obj); // true
}
}

How to Pause the Current Thread


try {
long delay = 7000; // 7 seconds
Thread.sleep(delay);
} catch (InterruptedException e) {
}
 

Sample Java Codes Copyright © 2008 Green Scrapbook Diary Designed by SimplyWP | Made free by Scrapbooking Software | Bloggerized by Ipiet Notez