Home > Uncategorized > Understanding java Collections Class

Understanding java Collections Class

Java Collections class can do lots of things on a given collections including binarySearch, sorting, finding minimum, maximum values, copy and so on.

 

Note that Collections class and Arrays class server very similar type of purpose. Many of the things in Collection class can also be achieved by Arrays class.

 

This is an example, I used to help my understanding.

 

Ref: http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/

 

class CollectionsExp{

public void test(){

List<Integer> numbers = new ArrayList<Integer>();

numbers.add(10);

numbers.add(3);

numbers.add(20);

Collections.sort(numbers);

for (Integer x: numbers){

System.out.println(x); // prints 3, 10, 20

}

Collections.reverse(numbers);

for (Integer x: numbers){

System.out.println(x); // prints 20, 10, 3

}

//sorting using custom comparator

Collections.sort(numbers, new Comparator<Integer>(){

public int compare(Integer x, Integer y){

return xy; // would print 3, 10, 20

// return y -x ; // would print 20, 10, 3

}

} );

for (Integer x: numbers){

System.out.println(x); // prints 3, 10, 20

}

}

}

2nd approach of sorting using Comparator class (More preferable to me)

class IntComparator implements Comparator{

public int compare (Object x, Object y){

return (Integer) y – (Integer) x;

}

}

class Test{

public void test(){

List<Integer> numbers = new ArrayList<Integer>();

numbers.add(10);

numbers.add(3);

numbers.add(20);

Collections.sort(numbers, new IntComparator());

}

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: