Wednesday 11 March 2015

ENUM


An enum is an abstract data type with values that each take on exactly one of a finite set of identifiers that you specify. Enums are typically
used to define a set of possible values that don’t otherwise have a numerical order, such as the suit of a card, or a particular season of
the year. Although each value corresponds to a distinct integer value, the enum hides this implementation so that you don’t inadvertently
misuse the values, such as using them to perform arithmetic. After you create an enum, variables, method arguments, and return types
can be declared of that type.


public enum Season {WINTER, SPRING, SUMMER, FALL}
Season e = Season.WINTER;

public Season m(Integer x, Season e1) {
if (e1 == Season.SUMMER) {
return Season.SUMMER;
}
else{
return Season.WINTER;
}
}

System.debug(m(1,Season.SUMMER));

Tuesday 10 March 2015

Uniqueness of map keys of user-defined types is determined by the equals and hashCode methods,


public class PairNumbers {
    Integer x,y;

    public PairNumbers(Integer a, Integer b) {
        x=a;
        y=b;
    }

    public Boolean equals(Object obj) {
        if (obj instanceof PairNumbers) {
            PairNumbers p = (PairNumbers)obj;
            return ((x==p.x) && (y==p.y));
        }
        return false;
    }

    public Integer hashCode() {
        return (31 * x) * y;
    }
}

Use case:

Map<PairNumbers, String> m = new Map<PairNumbers, String>();
PairNumbers p1 = new PairNumbers(1,2);
PairNumbers p2 = new PairNumbers(3,4);
// Duplicate key
PairNumbers p3 = new PairNumbers(1,2);
PairNumbers p4 = new PairNumbers(2,1);

m.put(p1, 'first');
m.put(p2, 'second');
m.put(p3, 'third');
m.put(p4, 'third');


// Map size is 2 because the entry with 
// the duplicate key overwrote the first entry.
System.assertEquals(2, m.size());

// Use the == operator
if (p1 == p3) {
    System.debug('p1 and p3 are equal.');
}

// Perform some other operations
System.assertEquals(true, m.containsKey(p1));
System.assertEquals(true, m.containsKey(p2));
System.assertEquals(false, m.containsKey(new PairNumbers(5,6)));

for(PairNumbers pn : m.keySet()) {
    System.debug('Key: ' + pn);
}

List<String> mValues = m.values();
System.debug('m.values: ' + mValues);

// Create a set
Set<PairNumbers> s1 = new Set<PairNumbers>();
s1.add(p1);
s1.add(p2);
s1.add(p3);

// Verify that we have only two elements
// since the p3 is equal to p1.
System.assertEquals(2, s1.size());