Java – Bubble Sort Array Example

import java.util.Arrays;

/**
 * Algorithm
 *
 * 1] Compare each pair of adjacent elements from beginning
 * of an array and, if they are in reversed order, swap them.
 *
 * 2] If at least one swap has been done, repeat step 1.
 *
 */
public class MyBubbleSort {

	private void sortData(int[] data) {
		boolean swapDone = false;
		do {
			swapDone = false;
			for (int i = 0; i < data.length-1; i++) {
				if (data[i] > data[i+1]) {
					swapDone = true;
					int tmp = data[i];
					data[i] = data[i+1];
					data[i+1] = tmp;
				}
			}
		} while (swapDone == true);
	}

	public static void main(String[] args) {
		int[] data = {5,1,12,-5,16};
		System.out.println(Arrays.toString(data));

		new MyBubbleSort().sortData(data);
		System.out.println(Arrays.toString(data));
	}

}

Java – Synchronized HashMap Example

HashMap is a non-synchronized collection class. If we need to perform thread-safe operations on it then we must need to synchronize it explicitly.

Iterator should be used in a synchronized block even if we have synchronized the HashMap explicitly.

Map map = Collections.synchronizedMap(new HashMap());
...
// This doesn't need to be in synchronized block
Set set = map.keySet();
// Synchronizing on map, not on set
synchronized (map) {
    // Iterator must be in synchronized block
    Iterator iterator = set.iterator();
    while (iterator.hasNext()) {
        ...
    }
}

Java – Enum Example

public enum UserStatus {
    PENDING("P"), ACTIVE("A"), INACTIVE("I"), DELETED("D");

    private String statusCode;

    private UserStatus(String s) {
        statusCode = s;
    }

    public String getStatusCode() {
        return statusCode;
    }
}

public class EnumTest {

    public static void main(String[] args) {
        System.out.println(UserStatus.ACTIVE.getStatusCode());
    }

}

Page 1 of 712345...Last »