class sortVectors implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
if(o1<02){
return -1;
}else if(o1>o2)
return 1;
return 0;
}
}
public class sortVector{
public static void main(String[] args) {
// TODO Auto-generated method stub
Vector<Integer> vect = new Vector<Integer>();
System.out.println("Befor sorting");
for (int index = 0; index < 10; index++) {
int rand = (int) (1000 * Math.random());
vect.add(rand);
System.out.println(rand);
}
Collections.sort(vect,new sortVectors());
System.out.println("After Sorting");
for (Integer num : vect) {
System.out.println(num);
}
}
}
How to sort Integer Vector using Comparator and iterator?
Question
I want to create Integer
vector type Vector
and to insert random 10 numbers.
Then I want to sort the Vector
by using compareTo
and to send two arguments type numbers to compare it.
but I miss something. Many thanks for any help.
import java.util.*;
public class SortNumeric implements Comparable<SortNumeric>
{
private int ind =0;
public static void main(String args[])
{
Vector<Integer> vec = new Vector<>();
System.out.println("Befor sorting");
for (int index = 0; index < 10; index++)
{
int rand = (int)(1000*Math.random());
vec.add(rand);
System.out.println(rand);
}
Arrays.sort(vec);
System.out.println("After sorting");
for(Integer intnum : vec)
{
System.out.println(intnum);
}
}
public int getNextCompar(){
if (vec.hasNext() && this.ind < 5){
this.ind++;
return vec.next();
}else{return 0;}
}
public int compareTo(SortNumeric other)
{
return (int) (vec.next() - this.getNextCompar());
}
}
Solution
OTHER TIPS
You don't need to implement Comparable
for Integer
, hence no compareTo
is required. Also use Collections.sort
instead of Arrays.sort
. Here is your modified code example:
import java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String args[]) {
Vector<Integer> vec = new Vector<>();
System.out.println("Befor sorting");
for (int index = 0; index < 10; index++) {
int rand = (int) (1000 * Math.random());
vec.add(rand);
System.out.println(rand);
}
Collections.sort(vec);
System.out.println("After sorting");
for (Integer intnum : vec) {
System.out.println(intnum);
}
}
}
Check this SO question for more details:
If you want to sort an array in a specific order, you need to create a Comparator.
Comparable is used when you want to sort the objects of a particular class when used in a collection or array.
In your case, you need to use a Comparator.
class MyComparator extends Compartor
{
public int compare(Integer a, Integer b)
{
return a - b;
}
}
In your Main class, call Arrays.sort(vec, new MyComparator());