Tuesday, September 21, 2010

Sort Vector Element - Java

Ini contoh bagaimana nak sort/susun senarai dalam vector menggunakan comparator

/*

Sort Java Vector in descending order using comparator example

This java example shows how to sort elements of Java Vector in descending order

using comparator and reverseOrder method of Collections class.

*/

import java.util.Vector;

import java.util.Collections;

import java.util.Comparator;

public class SortVectorInDescendingOrderExample {

public static void main(String[] args) {

//create a Vector object

Vector v = new Vector();

//Add elements to Vector

v.add("1");

v.add("2");

v.add("3");

v.add("4");

v.add("5");

/*

To get comparator that imposes reverse order on a Collection use

static Comparator reverseOrder() method of Collections class

*/

Comparator comparator = Collections.reverseOrder();

System.out.println("Before sorting Vector in descending order : " + v);

/*

To sort an Vector using comparator use,

static void sort(List list, Comparator c) method of Collections class.

*/

Collections.sort(v,comparator);

System.out.println("After sorting Vector in descending order : " + v);

}

}

/*

Output would be

Before sorting Vector in descending order : [1, 2, 3, 4, 5]

After sorting Vector in descending order : [5, 4, 3, 2, 1]

*/

ini pula contoh bagaimana sort/susun vector yang mengandungi olement object

wall.iddDestinationDetails recordTemp = new wall.iddDestinationDetails();

int count, swap, temp;

do

{

swap = 0;

for (count = 0; count <>

{

wall.iddDestinationDetails record1 = (wall.iddDestinationDetails)vecTemp.elementAt(count);

wall.iddDestinationDetails record2 = (wall.iddDestinationDetails)vecTemp.elementAt(count+1);

if (record1.getCALL_ATTEMPT().compareTo(record2.getCALL_ATTEMPT())>0)

{

//swap

vecTemp.set(count,record2);

vecTemp.set(count+1,record1);

swap = 1;

}

}

}while (swap != 0);

No comments:

Post a Comment