Write a Java program to sort the elements of a Vector collection


The code you provided is written in Java and demonstrates how to sort elements in a vector using the Collections.sort method. Here's an explanation of what the code does:

  • It imports the necessary java.util package, which contains the Vector class, Collections class, and other utility classes.
  • It declares a class named SortElements.
  • Within the SortElements class, the main method is defined, which serves as the entry point for the program.
  • Inside the main method, a Vector<Integer> named vec_list is declared and initialized. This vector is used to store a list of integers.
  • The add method is called on the vec_list object multiple times to add integers to the vector.
  • The System.out.println statement is used to print the vector elements to the console.
  • The Collections.sort method is called, passing the vec_list as an argument. This method sorts the elements in the vector in ascending order.
  • Another System.out.println statement is used to print the sorted vector elements to the console.

Source Code

import java.util.*;
public class SortElements
{
	public static void main(String[] args)
	{
		Vector < Integer > vec_list = new Vector < Integer > ();
		vec_list.add(100);
		vec_list.add(20);
		vec_list.add(57);
		vec_list.add(40);
		vec_list.add(5);
		vec_list.add(60);
		vec_list.add(7);
		vec_list.add(66	);
		vec_list.add(35);
		vec_list.add(10);
 
		System.out.println("Vector Elements : " + vec_list);
 
		Collections.sort(vec_list);
 
		System.out.println("Sorted Vector Elements : " + vec_list);
	}
}

Output

Vector Elements : [100, 20, 57, 40, 5, 60, 7, 66, 35, 10]
Sorted Vector Elements : [5, 7, 10, 20, 35, 40, 57, 60, 66, 100]

Example Programs