Java Notes(2)

Collection, Collections

Collection: interface(List :LinkedList, ArrayList; Vector: Stack; Set)

Collections : a tool class

e.g. Collections.sort(list)

Collections.sort vs Arrays.sort

Collections.sort deals with object that from collection interface(list,set,vector,stack), arrays deals with array object.

e.g. Class temp contains an array and a list.

Arrays.sort(temp.array) Collections.sort(temp.list)


Default sorting in sort method uses merge sort. If we want to write our own sorting, overwrite comparator interface.

Comparator contains two methods: 1) compare 2) equal. Usually, we overwrite compare method.

public int compare(Object obj1, Object obj2)

return a positive number if obj1 > obj2

overwrite like this:  obj1 – obj2

An example using overwritten sort to solve sorting class’s problem:




(condition 1) && (condition 2) if 1 is false, the compiler won’t go check 2. Thus we need to be careful about the order.


iterator(import iterator package) is designed to help different types of variables to loop. It can be used as list.iterator();

There are three methods of iterator:

next(); hasNext(); remove();


get type


Sometimes we use instanceof to check if a is a sub-class object of A: x instanceof String. Return a boolean to check if x is String. Notice that you must check if x belongs to a class or not. You can’t use char or int here, but Character and Integer.

Ternary Operator

Ternary operator (condition)? A : B must the right side of =, because it’s an operator.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s