Automatically Sort Vector Elements

1 Comment

Vector class in java.util package is very easy to use. You can add objects of any type in a vector.

You don’t have to worry about declaring the size of the vector. You can just keep adding elements to your object and the vector will dynamically adjust the size. The vector will add elements one after other and will keep them in the order in which your insert them. It means that the elements in the vector are not sorted. Sometimes you need to sort elements in a vector. The Vector class does not offer any sorting mechanism. I created a subclass to sort elements in a vector.
It works with any class that implements Comparable interface or has a Compartor method. If you want elements of your own class sorted in a vector you will need to either make your class implement Comparable or create a Comparator method.


public class SortedVector extends Vector{
public SortedVector(){
super();
}
public void addElement(Object o){
super.addElement(o);
Collections.sort(this);
}
}

Here is a sample program showing how to use this class.

public static void main(String args[]){
SortedVector v =new SortedVector();
v.addElement(new Double(12));
v.addElement(new Double(320));
v.addElement(new Double(21));
System.out.println(v);
}

The output from this program is [12.0, 21.0, 320.0].

article clipper vert Automatically Sort Vector Elements
 

#1 Programming Language – Java

No Comments

According to TIOBE Programming Community Index Java is still the #1 programming language.

TIOBE Index gives an indication of the popularity of a programming language and is updated monthly.
The ratings are calculated by counting hits of the most popular search engines.
Ruby moved up from 13th to 10th position.

Following is the list of top 10 programming languages.
1. Java
2. C
3. (Visual) Basic
4. C++
5. PHP
6. Perl
7. C#
8. Python
9. JavaScript
10. Ruby

For complete results visit TIOBE website

article clipper vert #1 Programming Language   Java
 

Newer Entries