Home Java Beginners Sorting Array List in Java
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Sorting Array List in Java

Advertisement
This Java Tutorial section we demonstrates how to sort ArrayList in Java.

Sorting Array List in Java

In this example you will learn about sorting array list in java using an example. By default array list are sorted as the element are inserted into the list. In Java ArrayList extends AbstractList implements List Interface. ArrayList are created with the initial size and exceed when the element increased. This example will explain sorting of ArrayList using Comparator, Comparable and Collectiolns.sort() method. ArrayList are dynamic in nature so they are also called dynamic array. But standard array are not dynamic in nature once the array is created they cannot be grow or shrink, fixed in size. ArrayList doesn't have sort() method. We can use the sort method of the Collections class. It sorts the Collection object. Now, here is the example to sort an ArrayList in java .

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class SortArrayList{
 
	public static void main(String args[]){
 
		List list = new ArrayList();
 
		list.add("D");
		list.add("G");
		list.add("A");
		list.add("XX");
		list.add("HHH");
		list.add("KK");
		list.add("abc");
		list.add("123");
		list.add("980");
 
		//before sort
		System.out.println("ArrayList before sort");
		for(String var: list){
			System.out.println(var);
		}
 
		//sort the list
		Collections.sort(list);
 
		//after sorted
		System.out.println("ArrayList after sort");
		for(String var: list){
			System.out.println(var);
		}
	}
 
}

Output from the program

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 24, 2013

Related Tutorials

Ask Questions?    Discuss: Sorting Array List in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com