difference between int and integer


However, very different things are going on under the covers here. An int is a number; an Integer is a pointer that can reference an object that contains a number.


garbage collection

  • everything managed by garbage collector is on the heap
  • garbage collects the heap that has reference to.
  • stack: contiguous, easy to go up/down, methods place frames on stack
  • heap: stack has some variable pointed to heap

int i = 5; double d = 25.5; // on stack Object o = new Car(); Public static Foo = “foo”; // on heap

TUTORIAL http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html


Comparator interface

Define new class that implements Comparator interface, and pass an instance of the new class into comparator parameter.

The Comparator interface defines two methods: compare( ) and equals( ). The compare( ) method, shown here, compares two elements for order:
The compare Method:

int compare(Object obj1, Object obj2)

obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal. It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned.

By overriding compare( ), you can alter the way that objects are ordered. For example, to sort in reverse order, you can create a comparator that reverses the outcome of a comparison.
The equals Method:

The equals( ) method, shown here, tests whether an object equals the invoking comparator:

boolean equals(Object obj)

obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false.

Overriding equals( ) is unnecessary, and most simple comparators will not do so.




Comparable interface

make the Object implement the Comparable interface and override the compareTo() method

public class Fruit implements Comparable<Fruit>{ 
                // must override compareTo because it implements Comparable
                public int compareTo(Fruit compareFruit) {

		int compareQuantity = ((Fruit) compareFruit).getQuantity(); 

		//ascending order
		return this.quantity - compareQuantity;

		//descending order
		//return compareQuantity - this.quantity;

public class Employee implements Comparable<Employee> {
    private Name name;
    class Name{
        private String firstName;
        private String lastName;
    public int compareTo(Employee o) {
        if(this.name.firstName.compareTo(o.name.firstName) == 0){
            return this.name.lastName.compareTo(o.name.lastName);
        return this.name.firstName.compareTo(o.name.firstName);