Friday, February 12, 2010

Life in MCA CUSAT (Kerala)


Final Year Graduation

It was year 2000-01 and I was quite thrilled as well as tensed for the coming year.
My final year of graduation (in Hindu College, Delhi University). The coming year seemed to have lot of uncertainties; actually it was in the first year of my graduation when I had decided to go for MCA after my degree.
I was lucky get a room partner(Shivam Sinha) in the College hostel who was quite serious towards his studies. The biggest hurdle during those days were all the MCA entrance exams were in parallel to our graduation examination.
I remember, few days after I filled and posted my CUSAT (Cochin University of Science And Technology) application form, just out of something(I don't know) I told my roommate that I think I will be able to compete in this competition.
Between Mar to Jun '01 came a series of exams MCA + degree.
After few failures, finally I got first success in VIT (Vellore Institute of Technology) ; tired and frustrated of giving exams, I decided not to give any more MCA entrance exams and went home.
In June'2001 I went to Vellore for joining; till then I hadn't paid any fees there. After I reached there the next day I checked the internet and I saw that I had also cleared CUSAT exam. At that point I decided to leave Vellore and go to CUSAT.

Counseling in CUSAT
This was my first visit to Kerala and I was excited. I went with my mother as she wished to see various temples across Southern India and meet my brother who was then working in Infosys Mangalore.
During the counseling I met people for the first time with whom I was going to spend next coming three years. Bhattu, Pandey, Manoj, Pradeep and Juneja(popularly known as Junnu) were few of the people with whom I interacted on the counseling day.
The counseling went fine but I missed the free seats by 1 rank (these were 30 out 60 MCA seats which were fully funded by the Kerala Govt.) , and I was placed in Wait List No.1. So again a bit of disappointment; but I was quite confident to get the free seat and same happened few weeks later when one my friend of Hindu College decided not to join CUSAT as he had one more option(actually two of us from Hindu College joined CUSAT during counseling) .
I went a week earlier to Kochi, in order to submit my certificates and other docs; from there I had plan to go to my brother place for a weeks. This time again I stayed in the same hotel where I stayed during counseling, it was very near to Ernakulam Rly. St. but far from CUSAT. The next day I had to go to the University; I went directly to DCA (Dept. of Computer Appls). This time somehow I had no fear of ragging as I was quite used to that during my 10+2 and graduation hostel days. But to my luck I met a very humble super senior (Siju Sir) who nicely showed me to the labs and classrooms in the dept. He then advised me to visit hostel as well. When I went there(Siberia Hostel) someone advised me to go to a particular room (it was room of Dhiru Sir and Amritanshu Sir which I came to know later). As I entered I saw many people around 10 to 12 were sitting there, I casually went ahead and shook hand with each of them and introduced my self. Someone in the lot felt offended and scolded me for my behavior.
But it didn't became any uglier. When I was done, Amritanshu Sir who was also from Delhi Univ., came along with me to downstairs and gave me few tips and advice; I haven't still not forgotten his humble and nice attitude (Thanks Sir and hats of to you). As I came down he introduced me to two depressed looking faces then (they were my batch mates Munshi and RajKumar) who unknowingly came there 2 weeks earlier (the joining date for us was postponed by 2 weeks and all of us were also informed for the same).
By afternoon I came back to my hotel and by the late evening I was off toMangalore (my brother's house) on a bus.

Ist Semester - Exciting and Enthusiastic
It was 14th oct'2001 Sunday morning when I came back to Kochi from Mangalore (on bus); it was raining heavily there and I asked the bus conductor to drop me around the same hotel where I had stayed earlier. The city was all water logged, till my knees it was water; luckily I didn't had much luggage and it was manageable somehow. But when I came to the hotel all rooms there were already booked so I had to walk again to find some other hotel. By late evening everything was okay. Before that night I shifted back to my old hotel again.
Next day 15th Oct'2001 was our first day (in records) in DCA, CUSAT.
First day I decided to go in formals and the decision went right as seniors forced us to wear only formals till freshers party.
I interacted with many seniors and batch-mates. Our batch was divided into two groups each 30 students - Batch A and Batch B; I was in batch A. Batch B was rich in terms of gals crowd; we had only three gals in our batch. Ratio was bad 9:1.
Seniors inquired where I was staying and one of our Super Senior Prabhakar Sir offered me stay in his room as a guest. Still I remember meeting Junnu, Manoj and popular Pandey. That day I went back to hotel and decided to go shift next day.
Next day was nothing extraordinary except there were few more seniors who interacted with me(a soft alternative of ragging word interaction was used in CUSAT), Sheena our super senior was one among them (I still remember this as she wrote the incident in my slam book, she described the incidence as harsh but I never felt so). This day I shifted to Prabhakar's room in Siberia hostel, Manoj helped me in shifting (thanks buddy, I know its a bit late to say this).In hostel life was cool, but Prabhakar's room-mate Dilip Vedula was the coolest one, I wondered every night why every night he slept with a bucket side to his bed? (Because he boozed every night).Very sooner I made lot of friends. One evening we(Manoj, Juneja, Sinha and me, Chettri was lucky to reject the offer) decided to go the movie Jurassic Park-3 unknowingly that this was not permitted during ragging; the funny part was that near to the theatre, we saw Munshi with some seniors (during ragging period Munshi was seniors favorite guy) and instead of hiding from them we called them and started discussing about this movie. At night all of us got call at a senior room (the horrifying room of Pravesh Bhatia); there we were asked to say dialogues in the movie, all of us were stunned but to surprise of all of us Juneja started shouting Gua-Gua-Gua..... (perhaps he was imitating dinosaurs).
Soon my room (i.e., of Prabhakar and Vedula) became a hub for our batch guys mostly with whom I had developed intense friendship. Sinha mostly anxious (whenever he entered my room) and one day he broke mirror of Vedula and it was the time for us to create a story about mirror. We(Juneja, Manoj, Chawla, Chettri and me ) planned a story and told Sinha that this mirror was given by Vedula's younger brother at station when Vedula was leaving Vizag and this mirror means a lot to Vedula's family sentiments. Sinha was soon totally convinced and he bought a mirror from market and presented it to Vedula saying "Sir you can consider me also as your younger brother; please accept this mirror". To this he added "whenever you will see your face in the mirror you can see your brother and me on the other side of the mirror". And suddenly Vedula Sir couldnt stop himself from laughing and all of us also broke. Sinha was stunned and started chasing us in the corridors.
Another incident that i cant resist adding here that Manoj and me was asked (by Dhawan Sir our senior in Sanathana hostel) to rag Chinmaya Acharya who actually joined a bit later than all of us. As we started to rag him; I asked him 'what will you do if Aishwaray Rai comes to your room late at night, on this chinu replied that he will quietly go out of the room and wait outside.' Before things can go worse we stopped and told him the truth. Chinu didn't spoke to us for many days. With many such funny incidents weeks passed away.
During one of ragging session I was asked to prepare and present a speech on "IT industry recession" but that never happened. In one of such session Sreeja (Sreeju, smaller Sreeja), she had many nicknames as there were two Sreeja in our class, she presented a speech on Dosa ("I am what I ate for breakfast"); then after we started calling her Dosa (to avoid any further confusion) for rest of our days in CUSAT.
After few more weeks five (Manoj, Chettri, Juneja, Sinha and me) of us decided to rent a house.
We got a fairly good and very spacious house just next to the highway. Half of the house was rented to some automobiles LPG agency and they had a lady secretary to whom Manoj(and also the rest) use to peep regularly from his room ventilator.
Enjoying, laughing, ragging (also getting ragged) and peeping; many days passed away. Girish and Chawla were regular visitors to our house and they soon became integral part of our gang.
During those days I was appointed, by Alok Das Sir, as a member of 'Special Interest Group' alongwith Linu, Ritika and Ravjeet. For some reason Alok Sir showed a great confidence in me. Together we organized a seminar where an external lecturer came to give a speech on "IT industry Future". This seminar was a big success and we all us got lots of appreciation.
By now we five were well settled in our new house. Work among five of us in the room was well distributed: Sinha use to study, Junnu use to do face-wash, chettri mostly found filling drinking water from the tap outside, manoj doing pull ups on the ventilator and myself mostly sleeping and giving fundas and gyan to others.
Finally the most awaited day arrived, the freshers day. We all decided to betray the dress code (Chawla was propeller for this), but his idea was good so we all agreed.
Freshers day was nice but the night was even nicer when we offered unlimited free drinks from seniors @ Chandani Bar. It was first and last(till now) unlimited free drinks offer in my life, but then I was not a good drinker(in fact I was a starter).
After drinks I Still remember Pandey's doing big big bakch*di; Joseph George singing the song 'Chaddi kya dekhte hoo.....chaddi utaar kar dekho naa.....', manoj becoming sophisticated and speaking in English, Chawla saying this is my 6th peg......
After drinks when we came back to our house; we found Sinha studying as usual.
Many days passed and came time for our 1st internals, Sinha did 17 times revisions for Graph theory.
All of us (roommates) did well in internals.
We found a new caterer Nepalis to deliver us food and it was a good choice over Punjabi Dhaba.
Then came the most awaited time (of Christmas vacations), all of us were excited to go home after those fearful days of ragging and exams. I still remember buying Kerala cashew-nuts for my home, but more than half I finished on the way. I was traveling along with Manoj (Pandey joined us in the last moment); journey was long (Kochi to Ranchi 48 hrs on slow Bokaro-Allepey Express) but it was exciting with two friends alongwith.
But there was much news of excitement from Delhi gang who traveled together on Kerala Express. These people not only enjoyed by sharing their foods and drinks but few also shared their berths with each other.
When we (manoj and me) came back; I was surprised to see a lot of people coming to station to receive us (actually Delhi gang arrived to Kochi one day earlier than us). One funny incident happened on train was that on any mid station when I asked manoj to come down and get his body stretched, he refused. But when our final station (Aluva) arrived where we had to actually get down with luggage, there I saw manoj walking and stretching on station and saying me "Arre yaar soocha thoda aaram kar loon, pata nahin apna station kab aayega".
On that night in our house people made Junnu (the biggest rather the smallest Kid in our class) to write a love letter for a girl in our class. He did that and next day he even went to her to deliver that. It was not fully accepted but he had some good time watching movie(Kabhie khushi kabhie Gham) together and carrying her bags, books and bottles whenever required.
After that; many days passed, everyday almost we went around places in Kochi like Marine Drive, Menaka, movie halls, Cherai beach etc. etc.
Soon 2nd internals passed by.
In Feb I went to Munger (in Bihar) to attend my sisters marriage, when returning it was a three nights journey from Munger to Kochi (I changed 3 trains also), the third morning when I had to get down in Kochi I kept sleeping and went one station ahead from where I had to catch a return bus.
Freaking and enjoying many more days passed away and came time for our first semester external exams. But then there was university staffs strike in all over kerala, and our exams were postponed indefinitely. Delhi gang once again went to their hometown. Me and manoj was left in the house. Also there were very less people in hostel and around. Everyday when going for lunch or dinner we came back with some visitor to just get some timepass. One day Amit Singh visited and luckily or rather unluckily(for Sinha) he found Sinha's diary in which he entered a hypothetical intimate love story of Sinha and a girl from our class (Sinha I think had never even talked to that girl till then). Next day when Maji visited we made him to read that diary, he was literally shocked and said "Sinha is a very dangerous and dirty guy".
Finally the strike broke and all our house mates came back. Soon exams dates were released and all of us were back into studies. Exams went well for all of us and now there was semester break and time to go back to home once again.
Time to say: Bye Bye First Sem.

Thursday, February 11, 2010

Java Design Patterns

---------Creating-and-destroying-objects-------
-----------------------------------------------------------------------------


Item 1: Consider providing static factory methods instead of constructors

One advantage of static factory methods is that, unlike constructors, they have names.
A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they're invoked.
A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type.
public static Foo getInstance(String key)
{

initMapIfNecessary();

Class c = (Class) implementations.get(key);

if (c == null) return new DefaultFoo();

(Foo) c.newInstance();
......


The main disadvantage of static factory methods is that classes without public or protected constructors cannot be subclassed.
A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods.



Item 2: Enforce the singleton property with a private constructor

//Singleton with final field
public class Elvis {
public static final Elvis INSTANCE = new Elvis();
private Elvis() {... }
...
The main advantage of the first approach is that the declarations of the members comprising the class make it clear that the class is a singleton: the public static field is final, so the field will always contain the same object reference.

//Singleton with static factory
public class Elvis {
private static final Elvis INSTANCE = new Elvis();

private Elvis() { ... }

public static Elvis getInstance() {

return INSTANCE;
}

...


The main advantage of the second approach is that it gives you the flexibility to change your mind about whether the class should be a singleton without changing the API.
To make a singleton class serializable, it is not sufficient merely to add implements Serializable to its declaration. To maintain the singleton guarantee, you must also provide a readResolve method. Otherwise, each deserialization of a serialized instance will result in the creation of a new instance

//readResolve method to preserve singleton property
private Object readResolve() throws ObjectStreamException {
//Return the one true Elvis and let the garbage collector take care of the Elvis impersonator.
return INSTANCE;
}



Item 3: Enforce noninstantiability with a private constructor

A class can be made noninstantiable by including a single explicit private constructor:

//Noninstantiable utility class
public class UtilityClass {
// Suppress default constructor for noninstantiability
private UtilityClass() {
//This constructor will never be invoked
}



Item 4: Avoid creating duplicate objects

An object can always be reused if it is immutable
String s = new String("silly"); // DON'T DO THIS!
String s = "No longer silly";

creates Calendar, TimeZone, and Date instances only once, when it is initialized, instead of creating them every time isBabyBoomer is invoked.

private static final Date BOOM_START;
private static final Date BOOM_END;
static {
Calendar gmtCal =
Calendar.getInstance(TimeZone.getTimeZone("GMT"));
gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
BOOM_START = gmtCal.getTime();
gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);
BOOM_END = gmtCal.getTime();
}
public boolean isBabyBoomer() {
return birthDate.compareTo(BOOM_START) >= 0 && birthDate.compareTo(BOOM_END)



Item 5: Eliminate obsolete object references

return elements[ --size ]; //wrong approach, will never be deference d, causes memory leak

Object result = elements[ --size ]; elements[size] = null; // Eliminate obsolete reference
return result;



Item 6: Avoid finalizers

There is no guarantee that finalizers will be executed promptly
Don't be seduced by the methods System.gc and System.runFinalization. They may increase the odds of finalizers getting executed, but they don't guarantee it. The only methods that claim to guarantee finalization are System.runFinalizersOnExit and its evil twin, Runtime.runFinalizersOnExit. These methods are fatally flawed and have been deprecated.

Never depend on a finalizer to update critical persistent state. For example, depending on a finalizer to release a persistent lock on a shared resource such as a database
To reclaim other nonmemory resources use try-finally block is generally used for this purpose.




-------Methods-Common-to-All-Objects-------
----------------------------------------------------------------------------


Item 7: Obey the general contract when overriding equals

Each instance of the class is inherently unique.
You don't care whether the class provides a “logical equality” test.
public boolean equals(Object o) {
throw new UnsupportedOperationException();
}

When a class has a notion of logical equality that differs from mere object identity, and a superclass has not already overridden equals to implement the desired behavior. This is generally the case for value classes, such as Integer or Date. A programmer who compares references to value objects using the equals method expects to find out whether they are logically equivalent, not whether they refer to the same object.

public boolean equals(Object o) {
if (!(o instanceof ColorPoint)) return false;
ColorPoint cp = (ColorPoint)o;

return cp.point.equals(point) && cp.color.equals(color);
}



Item 8: Always override hashCode when you override equals

Equal objects must have equal hash codes. Two distinct instances may be logically equal according to the class's equals method, but to the Object class's hashCode method, they're just two objects with nothing much in common. Therefore object's hashCode method returns two seemingly random numbers instead of two equal numbers as required by the contract.
public int hashCode() {
//for class Phone Number
int result = 17;

result = 37*result + areaCode;

result = 37*result + exchange;

result = 37*result + extension;

return result; }

Note: if two objects are equal according to the equals() method, they must have the same hashCode() value (although the reverse is not generally true).
Because on some architectures the address space is larger than the range of values for int, it is possible that two distinct objects could have the same hashCode(). If you override hashCode(), you can still use the System.identityHashCode() method to access this default value.
By defining equals() and hashCode() consistently, you can improve the usability of your classes as keys in hash-based collections.



Item 9: Always override toString

public String toString() { ... }



Item 10: Override clone judiciously

If a class implements Cloneable interface, Object's clone method returns a field-by-field copy of the object; otherwise it throws CloneNotSupportedException.

//Clone method to guarantee that instances cannot be cloned
public final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException(); }


All classes that implement Cloneable should override clone with a public method.This public method should first call super.clone and then fix any fields that need fixing

A fine approach to object copying is to provide a copy constructor.
A copy constructor is simply a constructor that takes a single argument whose type is the class containing the constructor, for example,
public Galaxy(Galaxy aGalaxy) {
this(aGalaxy.getMass(), aGalaxy.getName());

}
A minor variant is to provide a static factory in place of a constructor:
public static Galaxy newInstance(Galaxy aGalaxy) {
return new Galaxy(aGalaxy.getMass(), aGalaxy.getName());
}


When cloned original and copy are references to same object. (bit wise copy)
Any change to either variable effect the other.
Day bday = new Day(1975,11,11);
Day d = (Day) bday.clone();

d.advance(100);


Suppose you have a LinkedList l, and you want to copy it as an ArrayList. The clone method does not offer this functionality, but it's easy with a copy constructor: new ArrayList(l).

A deep copy occurs when an object is copied along with the objects to which it refers.
If a shallow copy is performed on obj1, then it is copied but its contained objects are not, they still refer to same contained objects.

Note: The default clone() method, inherited from Object, makes a shallow copy of the object. To achieve a deep copy, extra logic must be added that explicitly calls all contained objects' clone() methods, which in turn call their contained objects' clone() methods, and so on.



Item 11: Consider implementing Comparable

By implementing java.lang.Comparable interface, a class indicates that its instances have a natural ordering. Sorting an array of objects that implement Comparable is as simple as this:
Arrays.sort(a);
It is similarly easy to search, compute extreme values, and maintain automatically sorted collections of Comparable objects.


--------Classes-And-Interfaces---------
---------------------------------------------------------------

Item 12: Minimize the accessibility of classes and members

A well-designed module hides all of its implementation details, cleanly separating its API from its implementation. Modules then communicate with one another only through their APIs and are oblivious to each others' inner workings. This concept, known as information hiding or encapsulation
--For top-level (non-nested) classes and interfaces, there are only two possible access levels: package-private and public.
By making it package-private, you makeit part of the package's implementation rather than its exported API, and you can modify it, replace it, or eliminate it in a subsequent release without fear of harming existing clients. If you make it public, you are obligated to support it forever to maintain compatibility.

For members (fields, methods, nested classes, and nested interfaces) there are four possible
access levels, listed here in order of increasing accessibility:
  • private— The member is accessible only inside the top-level class where it is declared.
  • package-private— The member is accessible from any class in the package where it is declared. Technically known as default access, this is the access level you get if no access modifier is specified.
  • protected— The member is accessible from subclasses of the class where it is declared (subject to a few restrictions [JLS, 6.6.2]) and from any class in the package where it is declared.
  • public— The member is accessible from anywhere.

If a method overrides a superclass method, it is not permitted to have a lower access level in the subclass than it does in the superclass

A simple consequence is that classes with public mutable fields are not thread-safe.

Note that a nonzero-length array is always mutable, so it is nearly always wrong to have public static final array field. Even if array is immutable its elements can be added or removed.

//Potential security hole!
public static final Type[] VALUES = { ... };


The public array should be replaced by a private array and a public immutable list:

private static final Type[] PRIVATE_VALUES = { ... };
public static final List VALUES =
Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));



Item 13: Favor immutability

An immutable class is simply a class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object. The Java platform libraries contain many immutable classes, including String, the primitive wrapper classes, and BigInteger and BigDecimal. There are many good reasons for this: Immutable classes are easier to design, implement, and use than mutable classes. They are less prone to error and are more secure.

To make a class immutable, follow these five rules:
  1. Don't provide any methods that modify the object (known as mutators).
  2. Ensure that no methods may be overridden.
  3. Make all fields final.
  4. Make all fields private: public final fields can contain primitive values or references to immutable objects
  5. Ensure exclusive access to any mutable components.

Methods of immutable objects returns new instance of object say
public Complex add(Complex c) { return new Complex(re + c.re, im + c.im); }

Immutable objects are inherently thread-safe; they require no synchronization.
The only real disadvantage of immutable classes is that they require a separate object for each distinct value.
the String class, whose mutable companion is StringBuffer.
The list of rules for immutable classes at the beginning of this item says that no methods may modify the object and that all fields must be final.
constructors should create fully initialized objects with all of their invariants established


Item 14: Favor composition over inheritance

Inheritance breaks encapsulation. In other words, a subclass depends on the implementation details of its superclass for its proper function. The superclass's implementation may change from release to release, and if it does, the subclass may break, even though its code has not been touched.
Instead of extending an existing class, give your new class a private field that references an instance of the existing class. This design is called composition because the existing class becomes a component of the new one. Each instance method in the new class invokes the corresponding method on the contained instance of the existing class and returns the results. This is known as forwarding, and the methods in the new class are known as forwarding methods.
Wrapper class - uses composition in place of inheritance


Item 15: Design and document for inheritance or else prohibit it

Constructors must not invoke overridable methods, directly or indirectly.
The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will get invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, then the method will not behave as expected.



Item 16: Prefer interfaces to abstract classes

The most obvious difference between the two mechanisms is that abstract classes are permitted to contain implementations for some methods while interfaces are not. A more important difference is that to implement the type defined by an abstract class, a class must be a subclass of the abstract class.
Because Java permits only single inheritance, this restriction on abstract classes severely constrains their use as type definitions.
Interfaces allow the construction of nonhierarchical type frameworks.
public interface Singer {
AudioClip Sing(Song s);

}


public interface Songwriter {

Song compose(boolean hit);

}


public interface SingerSongwriter extends Singer, Songwriter {

AudioClip strum();

void actSensitive();

}




Item 17: Use interfaces only to define types

The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API.
You should export the constants with a noninstantiable utility class
Interfaces should be used only to define types.

// Constant interface pattern - do not use!
public interface PhysicalConstants {
static final double AVOGADROS_NUMBER = 6.02214199e23;

static final double BOLTZMANN_CONSTANT = 1.3806503e-23;

static final double ELECTRON_MASS = 9.10938188e-31;

}


// Constant utility class
public class PhysicalConstants {
private PhysicalConstants() { }
// Prevents instantiation
public static final double AVOGADROS_NUMBER = 6.02214199e23;

public static final double BOLTZMANN_CONSTANT = 1.3806503e-23;

public static final double ELECTRON_MASS = 9.10938188e-31;

}



Interfaces should be used only to define types. They should not be used to export constants.


Item 18: Favor static member classes over nonstatic

There are four kinds of nested classes: static member classes, nonstatic member classes, anonymous classes, and local classes.
All but the first kind are known as inner classes.

A static member class is a static member of its enclosing class and obeys the same accessibility rules as other static members. If it is declared private, it is accessible only within the enclosing class, and so forth.

The Operation class should be a public static member class of the Calculator class. Clients of the Calculator class could then refer to operations using names like Calculator.Operation.PLUS and Calculator.Operation.MINUS.

One common use of an anonymous class is to create a function object, such as a Comparator
Each instance of a nonstatic member class is implicitly associated with an enclosing instance of its containing class.
// Typical use of an anonymous class
Arrays.sort(args, new Comparator() {
public int compare(Object o1, Object o2) {

return ((String)o1).length() - ((String)o2).length();
}

});



----------------Methods---------------
-------------------------------------------------------


Item 23: Check parameters for validity

Most methods and constructors have some restrictions on what values may be passed into their parameters.
Typically the exception will be IllegalArgumentException, IndexOutOfBoundsException, or NullPointerException

Nonpublic methods should generally check their parameters using assertions rather than normal checks. If you are using a release of the platform that supports assertions (1.4 or later), you should use the assert construct; otherwise you should use a makeshift assertion mechanism.



Item 24: Make defensive copies when needed

public final class Period {

private final Date start;
private final Date end; public

Period(Date start, Date end) {
//Constructor
if (start.compareTo(end) > 0) throw new IllegalArgumentException(start + " after "+ end); this.start = start; this.end = end; }

public Date start() {return start;}

public Date end() {return end;}

... // Remainder omitted
}

// Attack the internals of a Period instance from client program
Date start = new Date();
Date end = new Date();

Period p = new Period(start, end);
end.setYear(78);
// Modifies internals of p!

To protect the internals of a Period instance from this sort of attack, it is essential to make a defensive copy of each mutable parameter to the constructor and to use the copies as components of the Period instance in place of the originals:

// Repaired constructor - makes defensive copies of parameters
public Period(Date start, Date end) {
this.start = new Date(start.getTime());

this.end = new Date(end.getTime());


if (this.start.compareTo(this.end) > 0)
throw new IllegalArgumentException(start +" after "+ end); }

defensive copies are made before checking the validity of the parameters, and the validity check is performed on the copies rather than on the originals.

do not use the clone method to make a defensive copy of a parameter whose type is subclassable by untrusted parties.

Date start = new Date();
Date end = new Date();

Period p = new Period(start, end);

p.end().setYear(78);
// Modifies internals of p!

To defend against the second attack, merely modify the accessors to return defensive copies of mutable internal fields:
// Repaired accessors - make defensive copies of internal fields
public Date start() {
return new Date(
start.getTime());
}

public Date end() {
return
new Date(end.getTime());
}




Item 26: Use overloading judiciously

The choice of which overloading to invoke is made at compile time.
Selection among overloaded methods is static, while selection among overridden methods is dynamic.



Item 27: Return zero-length arrays, not nulls

There is no reason ever to return null from an array-valued method instead of returning a zero-length array.


Item 28: Write doc comments for all exposed API elements

Notice the use of HTML metacharacters and tags in this doc comment. The Javadoc utility translates doc comments into HTML


------------------General Programming-------------

-------------------------------------------------------------------------------

Item 29: Minimize the scope of local variables

Prefer for loops to while loops, assuming the contents of the loop variable(s) aren't needed after the loop terminates.


Item 30: Know and use the libraries

The Collections Framework substantially reduces the amount of code necessary to do many mundane tasks. For example, suppose you have a vector of strings, and you want to sort it alphabetically. This one-liner does the job:
Collections.sort(v);
If you want to do the same thing ignoring case distinctions, use the following:
Collections.sort(v, String.CASE_INSENSITIVE_ORDER);


Item 31: Avoid float and double if exact answers are required

The float and double types are particularly ill-suited for monetary calculations because it is impossible to represent 0.1 (or any other negative power of ten) as a float or double exactly.



Item 32: Avoid strings where other types are more appropriate

Avoid the natural tendency to represent objects as strings when better data types exist or can be written.


Item 33: Beware the performance of string concatenation

Using the string concatenation operator repeatedly to concatenate n strings requires time quadratic in n. It is an unfortunate consequence of the fact that strings are immutable .When two strings are concatenated, the contents of both are copied.
use a StringBuffer in place of a String


Item 34: Refer to objects by their interfaces

If appropriate interface types exist, parameters, return values, variables, and fields should all be declared using interface types.
If you decide that you want to switch implementations, all you have to do is change the class name in the constructor (or use a different static factory)
// Good - uses interface as type
List subscribers = new Vector();
rather than this:
// Bad - uses class as type!
Vector subscribers = new Vector();

For example, the first declaration could be changed to read
List subscribers = new ArrayList();
and all of the surrounding code would continue to work.

The code surrounding the first declaration depended on the fact that Vector is synchronized, then it would be incorrect to substitute ArrayList for Vector in the declaration.
If an object belongs to such a class-based framework, it is preferable to refer to it by the relevant base class, which is typically abstract, rather than by its implementation class.


Item 35: Prefer interfaces to reflection

The reflection facility, java.lang.reflect, offers programmatic access to information about loaded classes. Given a Class instance, you can obtain Constructor, Method, and Field instances representing the constructors, methods, and fields of the class represented by the Class instance. These objects provide programmatic access to the class's member names, field types, method signatures, and so on.
Reflection allows one class to use another, even if the latter class did not exist when the former was compiled. This power, however, comes at a price:
You lose all the benefits of compile-time type checking, including exception checking.
The code required to perform reflective access is clumsy and verbose. It is tedious to write and difficult to read.
Performance suffers.
load classes on demand and use reflection to find out what methods and constructors they support.

Reflection is also appropriate for use in RPC systems to eliminate the need for stub compilers.
For many programs that must use a class unavailable at compile time, there exists at compile time an appropriate interface or superclass by which to refer to the class. If this is the case, you can create instances reflectively and access them normally via their interface or superclass.

The order in which these arguments are printed depends on the class specified in the first argument. If you specify “java.util.HashSet,” they're printed in apparently random order; if you specify “java.util.TreeSet,” they're printed in alphabetical order, as the elements in a TreeSet are sorted:
Class cl = Class.forName(args[0]);
Set s = (Set) cl.newInstance();

Disadvantages of reflection
Generates run-time errors, all of which would have been compile-time errors
It takes twenty lines of tedious code to generate an instance of the class from its name, whereas a constructor invocation would fit neatly on a single line.



Item 36: Use native methods judiciously

The Java Native Interface (JNI) allows Java applications to call native methods, which are special methods written in native programming languages such as C or C++.
class HelloWorld {
static {

System.loadLibrary("HelloWorld");
}

private native void print();

public static void main(String[] args) {

new HelloWorld().print();

}

}


javac HelloWorld.java


This command will generate a HelloWorld.class file in the current directory
javah -jni HelloWorld

The command shown above generates a file named HelloWorld.h.

Writing the C implementation (HelloWorld.c) of the native method
The JNI-style header file generated by javah helps you to write C or C++ implementations for the native method. The function that you write must follow the -prototype specified in the generated header file. You can implement the Hello-World.print method in a C file HelloWorld.c as follows:
#include
#include

#include
"HelloWorld.h"
JNIEXPORT
void JNICALL
Java_HelloWorld_print(JNIEnv *env, jobject obj) {
printf("Hello World!\n");
return;
}

Compiling the C implementation into a native library, creating Hello-World.dll or libHello-World.so
Now that all the necessary C code is written, you need to compile Hello-World.c and build this native library.


Item 37: Optimize judiciously

Item 38: Adhere to generally accepted naming conventions


---------------Exceptions----------------
------------------------------------------------------------


Item 39:Use exceptions only for exceptional conditions

// Horrible abuse of exceptions. Don't ever do this!
try {
int i = 0;

while(true)

a[i++].f();

} catch(ArrayIndexOutOfBoundsException e) {}


The infinite loop terminates by throwing, catching, and ignoring an ArrayIndexOutOfBoundsException when it attempts to access the first array element outside the bounds of the array.


Item 40:Use checked exceptions for recoverable conditions and run-time exceptions for programming errors

three kinds of throwables: checked exceptions, runtime exceptions, and errors.

Use checked exceptions for conditions from which the caller can reasonably be expected to recover. By throwing a checked exception, you force the caller to handle the exception in a catch clause or to propagate it outward

There are two kinds of unchecked throwables: run-time exceptions and errors.

They are identical in their behavior: Both are throwables that needn't, and generally shouldn't, be caught. If a program throws an unchecked exception or an error, it is generally the case that recovery is impossible and continued execution would do more harm than good. If a program does not catch such a throwable, it will cause the current thread to halt with an appropriate error message.

All of the unchecked throwables you implement should subclass RuntimeException.

Checked Exception: NamingException, FileNotFoundException
Uncheked Exceptions: NullPointerException, ArrayOutOfBoundException
Errors: OutofMemoryException, StackOverflowException, IOError


Item 41:Avoid unnecessary use of checked exceptions

the catch block almost always has the character of an assertion failure. The checked nature of the exception provides no benefit to the programmer, but it requires effort and complicates programs.
} catch(TheCheckedException e) { throw new Error("Assertion error"); // Should never happen!
}

How about this?
} catch(TheCheckedException e) { e.printStackTrace(); // Oh well, we lose.
System.exit(1); }

Item 42:Favor the use of standard exceptions


Item 43: Throw exceptions appropriate to the abstraction


higher layers should catch lower-level exceptions and, in their place, throw exceptions that are explainable in terms of the higher-level abstraction.
// Exception Translation or Exception Chaining
try {
// Use lower-level abstraction to do our bidding
...
} catch(LowerLevelException e) {
throw new HigherLevelException(...);
}
it may be appropriate to log the exception using some appropriate logging facility such as java.util.logging, which was introduced in release 1.4.


Item 44:Document all exceptions thrown by each method

Always declare checked exceptions individually, and document precisely the conditions under which each one is thrown using the Javadoc @throws tag.


Item 46:Strive for vetbfailure atomicity

After an object throws an exception, it is generally desirable that the object still be in a well-defined, usable state, even if the failure occurred in the midst of performing
an operation. This is especially true for checked exceptions, from which the caller is expected to recover. Generally speaking, a failed method invocation should leave the object in the state that it was in prior to the invocation. A method with this property is said to be failure atomic.
If an object is immutable, failure atomicity is free. If an operation fails, it may prevent a new object from getting created, but it will never leave an existing object in an inconsistent state because the state of each object is consistent when it is created and can't be modified thereafter.
For methods that operate on mutable objects, the most common way to achieve failure atomicity is to check parameters for validity before performing the operation


Item 47:Don't ignore exceptions

An empty catch block defeats the purpose of exceptions



-------------------Threads----------------
------------------------------------------------------------

Item 48: Synchronize access to shared mutable data

The synchronized keyword ensures that only a single thread will execute a statement or block at a time.
Not only does synchronization prevent a thread from observing an object in an inconsistent state, but it also ensures that objects progress from consistent state to consistent state by an orderly sequence of state transitions that appear to execute sequentially.

The language guarantees that reading or writing a single variable is atomic unless the variable is of type long or double. In other words, reading a variable other than a long or double is guaranteed to return a value that was stored into that variable by some thread, even if multiple threads modify the variable concurrently without synchronization.

While the atomicity guarantee ensures that a thread will not see a random value when reading atomic data, it does not guarantee that a value written by one thread will be visible to another: Synchronization is required for reliable communication between threads as well as for mutual exclusion.

Next, consider the process of stopping a thread. While the platform provides methods for involuntarily stopping a thread, these methods are deprecated because they are inherently unsafe—their use can result in object corruption. The recommended method of stopping a thread is simply to have the thread poll some field whose value can be changed to indicate that the thread is to stop itself. The field is typically a boolean or an object reference.

public void run() { //in run method
boolean done = false;
while (!stopRequested && !done) {
... // do what needs to be done.
}
}

The volatile modifier guarantees that any thread that reads a field will see the most recently written value.
whenever multiple threads share mutable data, each thread that reads or writes the data must obtain a lock.


Item 49: Avoid excessive synchronization

To avoid the risk of deadlock, never cede control to the client within a synchronized method or block. In other words, inside a synchronized region, do not invoke a public or protected method that is designed to be overridden. (Such methods are typically abstract, but occasionally they have a concrete default implementation.) From the perspective of the class containing the synchronized region, such a method is alien. The class has no knowledge of what the method does and no control over it. A client could provide an implementation of an alien method that creates another thread that calls back into the class.
do as little work as possible inside synchronized regions. Obtain the lock, examine the shared data, transform the data as necessary, and drop the lock.
When you are designing a mutable class, think about whether it should do its own synchronization.
classes StringBuffer and BufferedInputStream are thread-safe. Are almost always used by a single thread, so the locking they do is usually unnecessary.


Item 50: Never invoke wait outside a loop

The Object.wait method is used to make a thread wait for some condition. It must be invoked inside a synchronized region that locks the object on which it is invoked. This is the standard idiom for using the wait method:
synchronized (obj) {
while ()
obj.wait();
... // Perform action appropriate to condition
}
Always use the wait loop idiom to invoke the wait method. Never invoke it outside of a loop. The loop serves to test the condition before and after waiting.
It is often said that you should always use notifyAll. This is reasonable, conservative advice, assuming that all wait invocations are inside while loops. It will always yield correct results because it guarantees that you'll wake the threads that need to be awakened. You may wake some other threads too, but this won't affect the correctness of your program. These threads will check the condition for which they're waiting and, finding it false, will continue waiting.


Item 51: Don't depend on the thread scheduler

Any program that relies on the thread scheduler for its correctness or performance is likely to be nonportable.
There should be few runnable threads at any given time. This leaves the thread scheduler with very little choice: It simply runs the runnable threads till they're no longer runnable. As a consequence, the program's behavior doesn't vary much even under radically different thread scheduling algorithms.
Threads should not busy-wait, repeatedly checking a data structure waiting for something to happen. Besides making the program vulnerable to the vagaries of the scheduler, busy-waiting can greatly increase the load on the processor, reducing the amount of useful work that other processes can accomplish on the same machine.
A related technique, to which similar caveats apply, is adjusting thread priorities. Thread priorities are among the least portable features of the Java platform.
Thread.yield Causes the currently executing thread object to temporarily pause and allow other threads to execute.
Have Thread.yield is to artificially increase the concurrency of a program during testing.


Item 52: Document thread safety

The following list summarizes the levels of thread safety that a class can support.
  • immutable— Instances of this class appear constant to their clients. No external synchronization is necessary. Examples include String, Integer, and BigInteger
  • thread-safe— Instances of this class are mutable, but all methods contain sufficient internal synchronization that instances may be used concurrently without the need for external synchronization. Concurrent invocations will appear to execute serially in some globally consistent order. Examples include Random and java.util.Timer.
  • conditionally thread-safe— Like thread-safe, except that the class (or an associated class) contains methods that must be invoked in sequence without interference from other threads. To eliminate the possibility of interference, the client must obtain an appropriate lock for the duration of the sequence. Examples include Hashtable and Vector, whose iterators require external synchronization.
  • thread-compatible— Instances of this class can safely be used concurrently by surrounding each method invocation (and in some cases, each sequence of method invocations) by external synchronization. Examples include the general purpose collection implementations, such as ArrayList and HashMap.
  • thread-hostile— This class is not safe for concurrent use by multiple threads, even if all method invocations are surrounded by external synchronization. The System.runFinalizersOnExit method is thread-hostile, and has been deprecated.

Item 53: Avoid thread groups

Thread groups are largely obsolete.


---------------Serialization----------------
--------------------------------------------------------------

Serialization provides the standard wire-level object representation for remote communication, and the standard persistent data format for the JavaBeans™ component
architecture.

Item 54: Implement Serializable judiciously

When a class implements Serializable, its byte-stream encoding (or serialized form) becomes part of its exported API. Once you distribute a class widely, you are generally required to support the serialized form forever, just as you are required to support all other parts of the exported API.
A simple example of the constraints on evolution that accompany serializability concerns stream unique identifiers, more commonly known as serial version UIDs. Every serializable class has a unique identification number associated with it. If you do not specify the identification number explicitly by declaring a private static final long field named serialVersionUID, the system automatically generates it by applying a complex deterministic procedure to the class. The automatically generated value is affected by the class's name, the names of the interfaces it implements, and all of its public and protected members.
Normally, objects are created using constructors; serialization is an extralinguistic mechanism for creating objects. Whether you accept the default behavior or override it, deserialization is a “hidden constructor” with all of the same issues as other constructors.
A third cost of implementing Serializable is that it increases the testing burden associated with releasing a new version of a class.
In addition to binary compatibility, you must test for semantic compatibility. In other words, you must ensure both that the serialization-deserialization process succeeds and that it results in a faithful replica of the original object.

Classes designed for inheritance should rarely implement Serializable, and interfaces should rarely extend it.
There is one caveat regarding the decision not to implement Serializable. If a class that is designed for inheritance is not serializable, it may be impossible to write a serializable subclass. Specifically, it will be impossible if the superclass does not provide an accessible parameterless constructor. Therefore you should consider providing a parameterless constructor on nonserializable classes designed for inheritance.
Inner classes should rarely, if ever, implement Serializable. They use compiler-generated synthetic fields to store references to enclosing instances and to store values of local variables from enclosing scopes. How these fields correspond to the class definition is unspecified, as are the names of anonymous and local classes. Therefore, the default serialized form of an inner class is ill-defined. A static member class can, however, implement Serializable.


Item 55: Consider using a custom serialized form

The ideal serialized form of an object contains only the logical data represented by the object. It is independent of the physical representation.
The default serialized form is likely to be appropriate if an object's physical representation is identical to its logical content.


Item 56: Write readObject methods defensively

When an object is deserialized, it is critical to defensively copy any field containing an object reference that a client must not possess.
Any time you write a readObject method, adopt the mind-set that you are writing a public constructor that must produce a valid instance regardless of what byte stream it is given. Do not assume that the byte stream represents an actual serialized instance.


Item 57: Provide a readResolve method when necessary

If the class of an object being deserialized defines a readResolve method with the proper declaration, this method is invoked on the newly created object after it is deserialized.
If the Elvis class is made to implement Serializable, the following readResolve method suffices to guarantee the singleton property:
private Object readResolve() throws ObjectStreamException {
// Return the one true Elvis and let the garbage collector
// take care of the Elvis impersonator.
return INSTANCE;
}
This method ignores the deserialized object, simply returning the distinguished Elvis instance created when the class was initialized.
A readResolve method is necessary not only for singletons, but for all other instancecontrolled classes
The accessibility of the readResolve method is significant. If you place a readResolve method on a final class, such as a singleton, it should be private.

Sunday, February 7, 2010

Collection Framework

Configuration Utilities describes APIs used to access configuration data supplied when the application is deployed, or by the application's user.
Properties are configuration values managed as key/value pairs. From System Properties you can find information about the operating system, the user, and the version of Java.
The property names (keys) and values are stored in a Properties structure. A Properties object can also be used to store your own program properties in a file.

The following figure illustrates how a typical application might manage its configuration data with a Properties object over the course of its execution:



setProperty(String key, String value)
remove(Object key)
getProperty(String key)
containsKey(Object key)


On the Java platform, an application uses System.getEnv to retrieve environment variable values. Without an argument, getEnv returns a read-only instance of java.util.Map, where the map keys are the environment variable names, and the map values are the environment variable values.

A collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.
Core collection interfaces are the foundation of the Java Collections Framework.



Note also that the hierarchy consists of two distinct trees — a Map is not a true Collection.
Note that all the core collection interfaces are generic. For example, this is the declaration of the Collection interface.
public interface Collection...
The syntax tells you that the interface is generic.

A collection represents a group of objects known as its elements. The Collection interface is the least common denominator that all collections implement and is used to pass collections around and to manipulate them when maximum generality is desired.
For example, by convention all general-purpose collection implementations have a constructor that takes a Collection argument. This constructor, known as a conversion constructor, initializes the new collection to contain all of the elements in the specified collection, whatever the given collection's subinterface or implementation type. In other words, it allows you to convert the collection's type.
Suppose, for example, that you have a Collection c, which may be a List, a Set, or another kind of Collection. This idiom creates a new ArrayList (an implementation of the List interface), initially containing all the elements in c.
List list = new ArrayList(c);

The following shows the Collection interface:

public interface Collection extends Iterable {
// Basic operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(E element);
//optional
boolean remove(Object element);
//optional 1st occurrence
Iterator iterator();

// Bulk operations
boolean containsAll(Collection c);
//c1.containsAll(c2);
boolean addAll(Collection c);
//optional union c1Uc2
boolean removeAll(Collection c);
//optional difference c1-c2
boolean retainAll(Collection c);
//optional intersection
void clear();
//optional

// Array operations
Object[] toArray();
T[] toArray(T[] a);
}



There are two ways to traverse collections: (1) for-each and (2) using Iterators.

for (Object o : collection) //cannot call remove() method
System.out.println(o);

Iterator iterator()
Returns an iterator over the elements in this collection.

public interface Iterator {
boolean hasNext();
E next();
void remove();
//optional
}
Iterator itr = c.iterator();
while(itr.hasNext())
System.out.println(itr.next());


Collections class consists static methods that operate on or return collections.
Collections.singleton, which is a static factory method that returns an immutable Set containing only the specified element.

to remove all instances of a specified element, e, from a Collection, c.
c.removeAll(Collections.singleton(e));

suppose you want to remove all of the null elements from a Collection.
c.removeAll(Collections.singleton(null));

The array operations allow the contents of a Collection to be translated into an array.
Object[] a = c.toArray();
String[] a = (String[])c.toArray(); //collection has only String


===================Set===============

— a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction.
The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ. Two Set instances are equal if they contain the same elements.


The Java platform contains three general-purpose Set implementations:

HashSet, which stores its elements in a hash table, is the best-performing implementation; however it makes no guarantees concerning the order of iteration.

TreeSet, which stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashSet.

LinkedHashSet, which is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the set (insertion-order).

Suppose you have a Collection, c, and you want to create another Collection containing the same elements but with all duplicates eliminated. The following one-liner does the trick.
Collection noDups = new HashSet(c);


=============List================

— an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position). eg: vector

In addition to the operations inherited from Collection, the List interface includes operations for the following:
  • Positional access — manipulates elements based on their numerical position in the list
  • Search — searches for a specified object in the list and returns its numerical position
  • Iteration — extends Iterator semantics to take advantage of the list's sequential nature
  • Range-view — performs arbitrary range operations on the list.

public interface List extends Collection {
// Positional access
E get(int index);
E set(int index, E element);
//optional replaces element at index
boolean add(E element);
//optional adds new element at end of list

void add(int index, E element); //optional adds new element at given index
E remove(int index);
//optional
boolean addAll(int index, Collection c);
//optional add c starting from index


// Search
int indexOf(Object o);
int lastIndexOf(Object o);

// Iteration

ListIterator listIterator();
ListIterator listIterator(int index);

// Range-view (takes args as index values)
List subList(int from, int to);
}


  1. ArrayList, which is usually the better-performing implementation, and
  2. LinkedList which offers better performance under certain circumstances.

Also, 3. Vector has been retrofitted to implement List.


Consider the following assignment statement.
gift[5] = "golden rings"; //element at index 5 for normal array
The Vector equivalent is:
gift.setElementAt("golden rings", 5);
The List equivalent is:
gift.set(5, "golden rings");


List strengthens the requirements on the equals and hashCode methods so that two List objects can be compared for logical equality without regard to their implementation classes.
NOTE: Two List objects are equal if they contain the same elements in the same order.

The set and remove operations return the old value that is being overwritten or removed; the Vector counterparts (setElementAt and removeElementAt) return nothing (void).

static void shuffle(List list)
Randomly permutes the specified list using a default source of randomness.
Collections.shuffle(list, new Random()); //permutes with specified source of Random
[a, b, c, d, e, f]---->[c, a, f, b, e, d]

List list = Arrays.asList(args); //This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.


List also provides a richer iterator, called a ListIterator, which allows you to traverse the list in either direction, modify the list during iteration, and obtain the current position of the iterator. The ListIterator interface follows.

public interface ListIterator extends Iterator {
boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove();
//optional
void set(E e);
//optional
void add(E e);
//optional
}


ListIterator listIterator()
Returns a list iterator of the elements in this list (in proper sequence).
ListIterator listIterator(int index)
Returns a list iterator of the elements in this list (in proper sequence), starting at the specified position in this list.
ListIterator it = list.listIterator(list.size());


This implies the behavior of the two boundary cases:
  1. a call to previousIndex when the cursor is before the initial element returns -1 and
  2. a call to nextIndex when the cursor is after the final element returns list.size().

List sub_list = _list.subList(from, to);
sl.clear(); //also clears these sub_list elements from main _list; similiarly if

add, set, remove commands executed on sublist, main list also changes
The semantics of the List returned by subList become undefined if elements are added to or removed from the backing List in any way other than via the returned List.


polymorphic algorithms in the Collections class apply specifically to List.
  • sort - sorts a List using a merge sort algorithm, which provides a fast, stable sort.
  • shuffle - randomly permutes the elements in a List.
  • reverse - reverses the order of the elements in a List.
  • rotate - rotates all the elements in a List by a specified distance.
  • swap - swaps the elements at specified positions in a List.
  • replaceAll - replaces all occurrences of one specified value with another.
  • fill - overwrites every element in a List with the specified value.
  • copy - copies the source List into the destination List.
  • binarySearch - searches for an element in an ordered List using the binary search algorithm.
  • indexOfSubList - returns the index of the first sublist of one List that is equal to another.
  • lastIndexOfSubList - returns the index of the last sublist of one List that is equal to another.


=============Queue================

— a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations. The Queue interface follows.
public interface Queue extends Collection {
E element();
boolean offer(E e);
E peek();
E poll();
E remove();
//no args reqd. removes on FIFO or priority
}

Each Queue method exists in two forms: (1) one throws an exception if the operation fails, and (2) the other returns a special value if the operation fails (either null or false, depending on the operation). The regular structure of the interface is illustrated in the following table.

Queue Interface Structure



Queues typically, but not necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, which order elements according to their values. (removes element based on priority), doesnt add null value gives NullPointerException.

It is possible for a Queue implementation to restrict the number of elements that it holds; such queues are known as bounded. Some Queue implementations in java.util.concurrent(ArrayBlockingQueue, PriorityBlockingQ, LinkedBlockingQ) are bounded, but the implementations in java.util (LinkedList, PriorityQ) are not.

Whatever ordering the head of the queue is the element that would be removed by a call to remove or poll. The remove and poll methods differ in their behavior only when the queue is empty. Under these circumstances, remove throws NoSuchElementException, while poll returns null.

The add method, which Queue inherits from Collection, inserts an element unless it would violate the queue's capacity restrictions, in which case it throws IllegalStateException. The offer method, which is intended solely for use on bounded queues, differs from add only in that it indicates failure to insert an element by returning false.

The element and peek methods return, but do not remove, the head of the queue. They differ from one another in precisely the same fashion as remove and poll: If the queue is empty, element throws NoSuchElementException, while peek returns null.
Queue implementations generally do not allow insertion of null elements. The LinkedList implementation (also implements List interface), which was retrofitted to implement Queue, is an exception.

Queue implementations generally do not define element-based versions of the equals and hashCode methods but instead inherit the identity-based versions from Object.
The Queue interface does not define the blocking queue methods, which are common in concurrent programming. These methods, which wait for elements to appear or for space to become available, are defined in the interface java.util.concurrent.BlockingQueue, which extends Queue.



=============Map================


— A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Multiple keys can map same value. A Key can also map to the null Value. It models the mathematical function abstraction.

The Map interface follows.

public interface Map {

// Basic operations
V put(K key, V value);
// if key is already present, overwrite the value for same key
V get(Object key);
// gets value for the key else returns null
V remove(Object key);
// removes key-value mapping if present else returns null
boolean containsKey(Object key);
boolean containsValue(Object value);
int size();
boolean isEmpty();

// Bulk operations
void putAll(Map m);
void clear();
// removes all mappings from Map

// Collection Views (provides only means to iterate over Map)
public Set keySet();
//the set of keys(unique)contained in Map
public Collection values();
//this collection is not a set, as multiple keys can map same value
public Set<>> entrySet();
//small nested interface called Map.Entry, the type of the elements in this Set

// Interface for entrySet elements
public interface Entry {
K getKey();
V getValue();
V setValue(V value);
}
}


The Java platform contains three general-purpose Map implementations:

HashMap, which stores its elements(keys) in a hash table, is the best-performing implementation; however it makes no guarantees concerning the order of iteration.

TreeMap, which stores its elements in a red-black tree, orders its elements(keys) based on their values; it is substantially slower than HashSet.

LinkedHashMap, which is implemented as a hash table with a linked list running through it, orders its elements(keys) based on the order in which they were inserted into the Map (insertion-order).


Map is an interface, while Hashtable is a concrete implementation.
The following are the major differences:
  • Map provides Collection views instead of direct support for iteration via Enumeration objects. Collection views greatly enhance the expressiveness of the interface.
  • Map allows you to iterate over keys, values, or key-value pairs; Hashtable does not provide the third option.
  • Map provides a safe way to remove entries in the midst of iteration; Hashtable did not.
  • Finally, Map fixes a minor deficiency in the Hashtable interface. Hashtable has a method called contains, which returns true if the Hashtable contains a given value. Map improves the interface's consistency — containsValue parallels containsKey.


Like the Setand Listinterfaces, Map strengthens the requirements on the equals and hashCode methods so that two Map objects can be compared for logical equality without regard to their implementation types. Two Map instances are equal if they represent the same key-value mappings.

The following one-liner creates a new HashMap initially containing all of the same key-value mappings as m.
Map copy = new HashMap(m);

Set s = m.keySet();
//returns set of keys
Set> em = m.entrySet();
System.out.println("SET Entry Map:" +em);
for(Map.Entry e:em){
System.out.println("Entry:"+e+"Key:"+e.getKey()+"Val:"+e.getValue());
}


With all three Collection views, calling an Iterator's remove operation removes the associated entry from the backing Map, assuming that the backing Map supports element removal to begin with.
// Filter a map based on some property of its keys.
for (Iterator it = m.keySet().iterator(); it.hasNext(); )
if (it.next().isBogus())
it.remove();
//also removes entry from Map m


The Collection views support element removal in all its many forms — remove, removeAll, retainAll, and clear operations, as well as the Iterator.remove operation.
The Collection views do not support element addition under any circumstances.

if (m1.entrySet().containsAll(m2.entrySet())) { //whether the first Map contains all the key-value mappings in the second

if (m1.keySet().equals(m2.keySet())) { //whether two Map objects contain mappings for all of the same keys


Suppose you want to know all the keys common to two Map objects.
Set commonKeys = new HashSet(m1.keySet());
commonKeys.retainAll(m2.keySet());

Suppose you want to remove all of the key-value pairs that one Map has in common with another.
m1.entrySet().removeAll(m2.entrySet());

Suppose you want to remove from one Map all of the keys that have mappings in another.
m1.keySet().removeAll(m2.keySet());

All employee maps to their managers (Map name managers). To know who all the "individual contributors" (or nonmanagers) are.
Set individualContributors = new HashSet(managers.keySet());
individualContributors.removeAll(managers.values());

To fire all the employees who report directly to some manager, Simon.
Employee simon = ... ;
managers.values().removeAll(Collections.singleton(simon));

Collections.singleton, a static factory method that returns an immutable Set with the single, specified element.


A multimap is like a Map but it can map each key to multiple values. It's a fairly simple matter to use a Map whose values are List instances as a multimap.
Map> m = new HashMap>();



=
======Object-Ordering========

A List l may be sorted as follows.
Collections.sort(l);

If the List consists of String elements, it will be sorted into alphabetical order. If it consists of Date elements, it will be sorted into chronological order. String and Date both implement the Comparable interface.

Interface Comparable implementations provide a natural ordering for a class, which allows objects of that class to be sorted automatically.

If you try to sort a list, the elements of which do not implement Comparable, Collections.sort(list) will throw a ClassCastException.

Similarly, Collections.sort(list, comparator) will throw a ClassCastException if you try to sort a list whose elements cannot be compared to one another using the comparator.

Elements that can be compared to one another are called mutually comparable. Although elements of different types may be mutually comparable, none of the classes listed here permit interclass comparison.

The java.lang.Comparable interface consists of the following method.

public interface Comparable {
public int compareTo(T o);
}


The compareTo method compares the receiving object with the specified object and returns a negative integer, 0, or a positive integer depending on whether the receiving object is less than, equal to, or greater than the specified object. If the specified object cannot be compared to the receiving object, the method throws a ClassCastException.


public class Name implements Comparable {
....
public boolean equals(Object o) {
if (!(o instanceof Name)) return false;
Name n = (Name) o;
return n.firstName.equals(firstName) && n.lastName.equals(lastName); //internally uses String equals() method
}
public int hashCode() {
return 31 * firstName.hashCode() + lastName.hashCode();
}
public int compareTo(Name n) {
int lastCmp = lastName.compareTo(n.lastName); //internally uses String CompareTo() method for lastName comparison
return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));
}
}
public class NameSort {
List names = Arrays.asList(nameArray);
Collections.sort(names);
.....


To do either of these things, you'll need to provide a Comparator — an object that encapsulates an ordering. Like the Comparable interface, the Comparator interface consists of a single method.

public interface Comparator {
int compare(T o1, T o2);
}


The compare method compares its two arguments, returning a negative integer, 0, or a positive integer depending on whether the first argument is less than, equal to, or greater than the second. If either of the arguments has an inappropriate type for the Comparator, the compare method throws a ClassCastException.

public class NameSort {
static final Comparator SENIORITY_ORDER = new Comparator() {
public int compare(Name e1, Name e2) {
return e2.hireDate().compareTo(e1.hireDate()); //calls Date class compareTo() method
}
};
List names = Arrays.asList(nameArray);
Collections.sort(names, SENIORITY_ORDER);
.....



====
====Sorted-Set==========

A SortedSet is a Set that maintains its elements in ascending order, sorted according to the elements' natural ordering or according to a Comparator provided at SortedSet creation time.

In addition to the normal Set operations, the SortedSet interface provides operations for the following:
  • Range view — allows arbitrary range operations on the sorted set
  • Endpoints — returns the first or last element in the sorted set
  • Comparator access — returns the Comparator, if any, used to sort the set

Implementations: TreeSet

The code for the SortedSet interface follows.
public interface SortedSet extends Set {
// Range-view (Takes args as element values)
SortedSet subSet(E fromElement, E toElement);
SortedSet headSet(E toElement);
//first element to specified head
SortedSet tailSet(E fromElement);
//specified tail to last element

// Endpoints
E first();
E last();

// Comparator access
Comparator comparator();
}


The operations that SortedSet inherits from Set behave identically on sorted sets and normal sets with two exceptions:
  1. The Iterator returned by the iterator operation traverses the sorted set in order.
  2. The array returned by toArray contains the sorted set's elements in order.

All elements inserted into an sorted set must implement the Comparable interface (or be accepted by the specified Comparator). Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) (or comparator.compare(e1, e2)) must not throw a ClassCastException for any elements e1 and e2 in the sorted set.

TreeSet took the approach that it did, it also provides a constructor that takes a SortedSet and returns a new TreeSet containing the same elements sorted according to the same criterion.

SortedSet implementations also provide, by convention, a constructor that takes a Comparator and returns an empty set sorted according to the specified Comparator. If null is passed to this constructor, it returns a set that sorts its elements according to their natural ordering.

The range-view operations are somewhat analogous to those provided by the List interface, but there is one big difference. Range views of a sorted set remain valid even if the backing sorted set is modified directly. Changes to the range-view write back to the backing sorted set and vice versa.

Sorted sets provide three range-view operations. The first, subSet, takes two endpoints, like subList. Rather than indices, the endpoints are objects and must be comparable to the elements in the sorted set, using the Set's Comparator or the natural ordering of its elements, whichever the Set uses to order itself. Like subList, the range is half open, including its low endpoint but excluding the high one.

including "doorbell" but excluding "pickle", are contained in a SortedSet of strings called dictionary:
int count = dictionary.subSet("doorbell", "pickle").size();

the following one-liner removes all the elements beginning with the letter f.
dictionary.subSet("f", "g").clear();

st.subSet("d", "e").size(); //No. of words that starts with 'd'

Although it isn't entirely obvious, the successor of a string s in String's natural ordering is s + "\0" — that is, s with a null character appended.


Thus, the following one-liner tells you how many words between "doorbell" and "pickle", including doorbell and pickle, are contained in the dictionary.
count = dictionary.subSet("doorbell", "pickle\0").size();

Use the following to calculate the number of words between "doorbell" and "pickle", excluding both.
count = dictionary.subSet("doorbell\0", "pickle").size();

The SortedSet interface contains operations to return the first and last elements in the sorted set, not surprisingly called first and last

The SortedSet interface contains an accessor method called comparator that returns the Comparator used to sort the set, or null if the set is sorted according to the natural ordering of its elements.



====
=====Sorted-Map=========


A SortedMap is a Map that maintains its entries in ascending order, sorted according to the keys' natural ordering, or according to a Comparator provided at the time of the SortedMap creation.

The SortedMap interface provides operations for normal Map operations and for the following:
  • Range view — performs arbitrary range operations on the sorted map
  • Endpoints — returns the first or the last key in the sorted map
  • Comparator access — returns the Comparator, if any, used to sort the map

The following interface is the Map analog of SortedSet.

public interface SortedMap extends Map{
Comparator comparator();
SortedMap subMap(K fromKey, K toKey);
SortedMap headMap(K toKey);
SortedMap tailMap(K fromKey);
K firstKey();
K lastKey();
}


The operations SortedMap inherits from Map behave identically on sorted maps and normal maps with two exceptions:
  1. The Iterator returned by the iterator operation on any of the sorted map's Collection views traverse the collections in order.
  2. The arrays returned by the Collection views' toArray operations contain the keys, values, or entries in order.

Implementations: TreeMap

TreeMap took the approach it did, it also provides a constructor that takes a SortedMap and returns a new TreeMap containing the same mappings as the given SortedMap, sorted according to the same criterion.

SortedMap implementations also provide, by convention, a constructor that takes a Comparator and returns an empty map sorted according to the specified Comparator. If null is passed to this constructor, it returns a Map that sorts its mappings according to their keys' natural ordering.



==
==GeneralPurpose-Implementations====



All permit null elements, keys, and values. None are synchronized (thread-safe). All have fail-fast iterators, which detect illegal concurrent modification during iteration and fail quickly .
All are Serializable and all support a public clone method.

The legacy collections Vector and Hashtable are synchronized.
the Wrapper Implementations section, allow any collection to be transformed into a synchronized collection.

The java.util.concurrent package provides concurrent implementations of the BlockingQueue interface, which extends Queue, and of the ConcurrentMap interface, which extends Map.


General-Purpose Set Implementations

There are three general-purpose Set implementations — HashSet, TreeSet, and LinkedHashSet.

HashSet: HashSet is much faster, initial capacity, the default is 16.
Set s = new HashSet(64);//initial capacity is 64.

TreeSet: If you need to use the operations in the SortedSet interface, or if value-ordered iteration is required, use TreeSet

LinkedHashSet: Implemented as a hash table with a linked list running through it, it provides insertion-ordered iteration (least recently inserted to most recently) and runs nearly as fast as HashSet.


Special-Purpose Set Implementations

There are two special-purpose Set implementations — EnumSet and CopyOnWriteArraySet.

EnumSet is a high-performance Set implementation for enum types. All of the members of an enum set must be of the same enum type.
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
for (Day d : EnumSet.range(Day.MONDAY, Day.FRIDAY))
System.out.println(d);
//print from MONDAY to FRIDAY

CopyOnWriteArraySet (java.util.concurrent) is a Set implementation backed up by a copy-on-write array. All mutative operations, such as add, set, and remove, are implemented by making a new copy of the array; no locking is ever required. This implementation is only appropriate for sets that are rarely modified but frequently iterated. It is well suited to maintaining event-handler lists that must prevent duplicates.


General-Purpose List Implementations

There are two general-purpose List implementations — ArrayList and LinkedList.
ArrayList: it can take advantage of System.arraycopy when it has to move multiple elements at the same time. Think of ArrayList as Vector without the synchronization overhead. Positional access requires linear-time in a LinkedList and constant-time in an ArrayList. ArrayList has one tuning parameter — the initial capacity.

LinkedList: frequently add elements to the beginning of the List or iterate over the List to delete elements from its interior, you should consider using LinkedList. These operations require constant-time in a LinkedList and linear-time in an ArrayList.LinkedList has no tuning parameters and seven optional operations, one of which is clone. The other six are addFirst, getFirst, removeFirst, addLast, getLast, and removeLast. LinkedList also implements the Queue interface.



Special-Purpose List Implementations

CopyOnWriteArrayList is a List implementation backed up by a copy-on-write array. No synchronization is necessary, even during iteration, and iterators are guaranteed never to throw ConcurrentModificationException.
Example, it is not generally permssible for one thread to modify a Collection while another thread is iterating over it.
for (Iterator it = myCollection.iterator(); it.hasNext()) {
Object myObject = it.next();
if (someConditionIsTrue) {
// myCollection.remove(myObject); // wrong can throw ConcurrentModificationException
it.remove(myObject); // right
}
}

If you need synchronization, a Vector will be slightly faster than an ArrayList synchronized with Collections.synchronizedList.
But Vector has loads of legacy operations, so be careful to always manipulate the Vector with the List interface or else you won't be able to replace the implementation at a later time.


Map Implementations
Map implementations are grouped into general-purpose, special-purpose, and concurrent implementations.



General-Purpose Map Implementations

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the capacity is roughly doubled by calling the rehash method. As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs.

The three general-purpose Map implementations are HashMap, TreeMap and LinkedHashMap.

TreeMap: If you need SortedMap operations or key-ordered Collection-view iteration

HashMap: if you want maximum speed and don't care about iteration order

LinkedHashMap: if you want near-HashMap performance and insertion-order iteration. Note that insertion order is not affected if a key is re-inserted into the map. In other words, merely looking up the value associated with a key brings that key to the end of the map.
LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)
Constructs an empty LinkedHashMap instance with the specified initial capacity, load factor and ordering mode. accessOrder - the ordering mode - true for access-order, false for insertion-order.
Also, LinkedHashMap provides the removeEldestEntry method, which may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map. This makes it very easy to implement a custom cache.
Special-Purpose Map Implementations

There are three special-purpose Map implementations — EnumMap, WeakHashMap and IdentityHashMap.

EnumMap, which is internally implemented as an array, is a high-performance Map implementation for use with enum keys.
public enum Day { MON, TUE, WED }
public enum Val { one, two, three }
Map em = new EnumMap(Day.class);
em.put(Day.MON, Val.one);


WeakHashMap is an implementation of the Map interface that stores only weak references to its keys. Storing only weak references allows a key-value pair to be garbage-collected when its key is no longer referenced outside of the WeakHashMap.

IdentityHashMap is an identity-based Map implementation based on a hash table. This class is useful for topology-preserving object graph transformations, such as serialization or deep-copying. To perform such transformations, you need to maintain an identity-based "node table" that keeps track of which objects have already been seen.

Concurrent Map Implementations
The java.util.concurrent package contains the ConcurrentMap interface, which extends Map with atomic putIfAbsent, remove, and replace methods, and the ConcurrentHashMap implementation of that interface.

ConcurrentHashMap is a highly concurrent, high-performance implementation backed up by a hash table. This implementation never blocks when performing retrievals and allows the client to select the concurrency level for updates.



Queue Implementations

The Queue implementations are grouped into general-purpose and concurrent implementations. Queue Implementations
The Queue implementations are grouped into general-purpose and concurrent implementations.



General-Purpose Queue Implementations

LinkedList implements the Queue interface, providing FIFO queue operations for add, poll, and so on.

The PriorityQueue class is a priority queue based on the heap data structure. This queue orders elements according to an order specified at construction time, which can be the elements' natural ordering or the ordering imposed by an explicit Comparator.

The queue retrieval operations — poll, remove, peek, and element — access the element at the head of the queue. The head of the queue is the least element with respect to the specified ordering.

The iterator provided in method iterator is not guaranteed to traverse the elements of the PriorityQueue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).

The java.util.concurrent package contains a set of synchronized Queue interfaces and classes. Interface BlockingQueue extends Queue with operations that wait for the queue to become nonempty when retrieving an element and for space to become available in the queue when storing an element. This interface is implemented by the following classes:
  • LinkedBlockingQueue — an optionally bounded FIFO blocking queue backed by linked nodes
  • ArrayBlockingQueue — a bounded FIFO blocking queue backed by an array
  • PriorityBlockingQueue — an unbounded blocking priority queue backed by a heap
  • DelayQueue — a time-based scheduling queue backed by a heap
  • SynchronousQueue — a simple rendezvous mechanism that uses the BlockingQueue interface


Wrapper Implementations

Wrapper implementations delegate all their real work to a specified collection but add extra functionality on top of what this collection offers. For design pattern fans, this is an example of the decorator pattern.
library provides a static factory method. All these implementations are found in the
Collections class, which consists solely of static methods.
Synchronization Wrappers

The synchronization wrappers add automatic synchronization (thread-safety) to an arbitrary collection. Each of the six core collection interfaces — Collection, Set, List, Map, SortedSet, and SortedMap — has one static factory method.
public static Collection
synchronizedCollection(Collection c);
public static Set
synchronizedSet(Set s);
public static List
synchronizedList(List list);
public static Map
synchronizedMap(Map m);
public static SortedSet
synchronizedSortedSet(SortedSet s);
public static SortedMap
synchronizedSortedMap(SortedMap m);


Each of these methods returns a synchronized (thread-safe) Collection backed up by the specified collection.

List list = Collections.synchronizedList(new ArrayList());


In the face of concurrent access, it is imperative(important) that the user manually synchronize on the returned collection when iterating over it. The reason is that iteration is accomplished via multiple calls into the collection, which must be composed into a single atomic operation. The following is the idiom to iterate over a wrapper-synchronized collection.
Collection c = Collections.synchronizedCollection(myCollection);
synchronized(c) {
for (Type e : c)
foo(e);
}


If an explicit iterator is used, the iterator method must be called from within the synchronized block. Failure to follow this advice may result in nondeterministic behavior.


Unmodifiable Wrappers

Unlike synchronization wrappers, which add functionality to the wrapped collection, the unmodifiable wrappers take functionality away. In particular, they take away the ability to modify the collection by intercepting all the operations that would modify the collection and throwing an UnsupportedOperationException. Unmodifiable wrappers have two main uses, as follows:
To make a collection immutable once it has been built. In this case, it's good practice not to maintain a reference to the backing collection. This absolutely guarantees immutability.
To allow certain clients read-only access to your data structures. You keep a reference to the backing collection but hand out a reference to the wrapper. In this way, clients can look but not modify, while you maintain full access.
Like synchronization wrappers, each of the six core Collection interfaces has one static factory method.

public static Collection
unmodifiableCollection(Collection c);
public static Set
unmodifiableSet(Set s);
public static List
unmodifiableList(List list);
public static Map
unmodifiableMap(Map m);
public static SortedSet
unmodifiableSortedSet(SortedSet s);
public static SortedMap
unmodifiableSortedMap(SortedMap m);
Map unmodifiedMap = Collections.unmodifiableMap(modifiedMap);



Checked Interface Wrappers

The Collections.checked interface wrappers are provided for use with generic collections. These implementations return a dynamically type-safe view of the specified collection, which throws a ClassCastException if a client attempts to add an element of the wrong type. The generics mechanism in the language provides compile-time (static) type-checking, but it is possible to defeat this mechanism. Dynamically type-safe views eliminate this possibility entirely.



Convenience Implementations

This section describes several mini-implementations that can be more convenient and more efficient than general-purpose implementations when you don't need their full power. All the implementations in this section are made available via static factory methods rather than public classes.


List View of an Array

The java.util.ArraysCollections.nCopies method returns such a list. This implementation has two main uses. The first is to initialize a newly created List; for example, suppose you want an ArrayList initially consisting of 1,000 null elements. The following incantation does the trick. Of course, the initial value of each element need not be null. The second main use is to grow an existing List.
List list = new ArrayList(Collections.nCopies(100, (Type) null));
list.addAll(Collections.nCopies(50, type));


Immutable Singleton Set

Sometimes you'll need an immutable singleton Set, which consists of a single, specified element. The Collections.singleton method returns such a Set. One use of this implementation is to remove all occurrences of a specified element from a Collection.
c.removeAll(Collections.singleton(e));
say list.removeAll(Collections.singleton(type));


Empty Set, List, and Map Constants

The Collections class provides methods to return the empty Set, List, and Map — emptySet, emptyList, and emptyMap. The main use of these constants is as input to methods that take a Collection of values when you don't want to provide any values at all, as in this example.
tourist.declarePurchases(Collections.emptySet());
static List emptyList() Returns the empty list (immutable).
static Map emptyMap() Returns the empty map (immutable).
static Set emptySet() Returns the empty set (immutable).




==========Algorithms=========


All of them come from the Collections class, and all take the form of static methods whose first argument is the collection on which the operation is to be performed. The great majority of the algorithms provided by the Java platform operate on List instances, but a few of them operate on arbitrary Collection instances. This section briefly describes the following algorithms:

  • Sorting The sort algorithm reorders a List so that its elements are in ascending order according to an ordering relationship. The sort operation uses a slightly optimized merge sort algorithm that is fast and stable (It doesn't reorder equal elements).
Collections.sort(list);
The second form of sort takes a Comparator in addition to a List and sorts the elements with the Comparator.
static final Comparator SENIORITY_ORDER = new Comparator() {
public int compare(Name e2, Name e1) {
return e2.hireDate().compareTo(e1.hireDate());
}
};
Collections.sort(names, SENIORITY_ORDER);


  • Shuffling The shuffle algorithm does the opposite of what sort does, destroying any trace of order that may have been present in a List.
Collections.shuffle(list); Collections.shuffle(list, random); //Randomly permutes


Routine Data Manipulation The Collections class provides five algorithms for doing routine data manipulation on List objects, all of which are pretty straightforward:

  • reverse — reverses the order of the elements in a List.
  • fill — overwrites every element in a List with the specified value. This operation is useful for reinitializing a List.
  • copy — takes two arguments, a destination List and a source List, and copies the elements of the source into the destination, overwriting its contents. The destination List must be at least as long as the source. If it is longer, the remaining elements in the destination List are unaffected.
  • swap — swaps the elements at the specified positions in a List.
  • addAll — adds all the specified elements to a Collection. The elements to be added may be specified individually or as an array



  • Searching The binarySearch algorithm searches for a specified element in a sorted List. This algorithm has two forms. The first takes a List and an element to search for (the "search key"). This form assumes that the List is sorted in ascending order according to the natural ordering of its elements. The second form takes a Comparator in addition to the List and the search key, and assumes that the List is sorted into ascending order according to the specified Comparator. The sort algorithm can be used to sort the List prior to calling binarySearch. The return value is the same for both forms. If the List contains the search key, its index is returned. If not, the return value is (-(insertion point) - 1)
int pos = Collections.binarySearch(list, key);
if (pos <>

  • Composition The frequency and disjoint algorithms test some aspect of the composition of one or more Collections:
--frequency — counts the number of times the specified element occurs in the specified collection
--disjoint — determines whether two Collections are disjoint; that is, whether they contain no elements in common

  • Finding Extreme Values The min and the max algorithms return, respectively, the minimum and maximum element contained in a specified Collection. Both of these operations come in two forms. The simple form takes only a Collection and returns the minimum (or maximum) element according to the elements' natural ordering. The second form takes a Comparator in addition to the Collection and returns the minimum (or maximum) element according to the specified Comparator.




===
====Custom_Implementation========

Writing a custom implementation is surprisingly easy. The Java Collections Framework provides abstract implementations designed expressly to facilitate custom implementations. We'll start with the following example of an implementation of Arrays.asList.
public static List asList(T[] a) {
return new MyArrayList(a);
}

private static class MyArrayList extends AbstractList {

private final T[] a;

MyArrayList(T[] array) {
a = array;
}

public T get(int index) {
return a[index];
}

public T set(int index, T element) {
T oldValue = a[index];
a[index] = element;
return oldValue;
}

public int size() {
return a.length;
}
}


Believe it or not, this is very close to the implementation that is contained in java.util.Arrays. It's that simple! You provide a constructor and the get, set, and size methods, and AbstractList does all the rest.(need to override abstrct methods only, rest of methods are not abstract) You get the ListIterator, bulk operations, search operations, hash code computation, comparison, and string representation for free.

The following list summarizes the abstract implementations:
  • AbstractCollection — a Collection that is neither a Set nor a List. At a minimum, you must provide the iterator and the size methods.
  • AbstractSet — a Set; use is identical to AbstractCollection.
  • AbstractList — a List backed up by a random-access data store, such as an array. At a minimum, you must provide the positional access methods (get and, optionally, set, remove, and add) and the size method. The abstract class takes care of listIterator (and iterator).
  • AbstractSequentialList — a List backed up by a sequential-access data store, such as a linked list. At a minimum, you must provide the listIterator and size methods. The abstract class takes care of the positional access methods. (This is the opposite of AbstractList.)
  • AbstractQueue — at a minimum, you must provide the offer, peek, poll, and size methods and an iterator supporting remove.
  • AbstractMap — a Map. At a minimum you must provide the entrySet view. This is typically implemented with the AbstractSet class. If the Map is modifiable, you must also provide the put method.



======Compatibility =======


The Java Collections Framework was designed to ensure complete interoperability between the core collection interfaces and the types that were used to represent collections in the early versions of the Java platform: Vector, Hashtable, array, and Enumeration.


Upward Compatibility

Suppose the old API returns an array of objects and the new API requires a Collection. The Collections Framework has a convenience implementation that allows an array of objects to be viewed as a List. You use Arrays.asList to pass an array to any method requiring a Collection or a List.

Foo[] result = oldMethod(arg);
newMethod(Arrays.asList(result));

If the old API returns a Vector or a Hashtable, you have no work to do at all because Vector was retrofitted to implement the List interface, and Hashtable was retrofitted to implement Map.

The Collections.list method translates an Enumeration into a Collection.
Enumeration e = oldMethod(arg);
newMethod(Collections.list(e));



Backward Compatibility


Suppose the new API returns a Collection, and the old API requires an array of Object. As you're probably aware, the Collection interface contains a toArray method designed expressly for this situation.

Collection c = newMethod();
oldMethod(c.toArray());

If the old API requires a Vector, the standard collection constructor comes in handy.

Collection c = newMethod();
oldMethod(new Vector(c));
The case where the old API requires a Hashtable is handled analogously.
Map m = newMethod();
oldMethod(new Hashtable(m));

This is a static factory method that takes a Collection and returns an Enumeration over the elements of the Collection.

Collection c = newMethod();
oldMethod(Collections.enumeration(c));