📌  相关文章
📜  如何使用Java的可比较接口对向量元素进行排序?

📅  最后修改于: 2022-05-13 01:55:51.128000             🧑  作者: Mango

如何使用Java的可比较接口对向量元素进行排序?

Vector 是集合的子接口。如果我们想将一组单个对象表示为允许重复且必须保留插入顺序的单个实体,那么我们应该选择向量。它是一个可调整大小或可增长的数组。它实现了 Serializable、Cloneable 和 RandomAccess 接口。向量中存在的每个方法都是同步的,因此向量对象是线程安全的。

可比接口 用于对用户定义类的对象进行排序。这个接口存在于Java.lang' 包,它只包含一个方法 compareTo(object)。但是它只提供了一个单一的排序序列,即我们可以基于单个数据成员对元素进行排序。

compareTo()方法

此方法用于将当前对象与指定对象进行比较,并根据两个对象的比较结果返回三个值。使用 Comparable 接口,我们可以对 String 类对象、用户定义类对象和所有包装类对象的元素进行排序。

句法:



public int compareTo(Object obj); 

返回类型:整数值

  • 当且仅当第一个对象必须在第二个对象之前出现时为负值。
  • 正值当且仅当第一个对象必须在第二个对象之后。
  • 当且仅当第一个对象等于第二个对象时为零。

集合是一个 实用程序类存在于Java.util '包中,用于为集合对象定义多种实用程序方法,例如排序、搜索和反转等。

为了对列表的元素进行排序,Collections 类定义了两种排序方法,如下所示:

  1. public static void sort(List l):根据默认的自然排序顺序进行排序。在这种情况下,列表应包含同构对象或可比较对象,否则我们将获得运行时异常,列表不应包含 null 否则我们将获得 NullPointerException。
  2. public static void sort(List l, Comparator c):根据自定义排序顺序进行排序。

执行:

考虑创建一个自定义类名 Students,它实现了我们在其中获取每个学生的 id 的可比较接口。在 driver 类中,我们创建了一个 student 类类型的向量,然后我们可以通过比较学生的 id 使用可比接口对向量元素进行排序。

示例 1:

Java
// Java Program to Sort Vector Elements
// using Comparable Interface
 
// Importing Collections and Vector classes from
// java.util package
import java.util.*;
import java.util.Collections;
import java.util.Vector;
 
// Class 1
// Helper class
// Class implementing comparable interface
class Student implements Comparable {
 
    // Declaring a variable
    private int id;
   
    // Initializing the above variable through
    // self constructor of this class
    public Student(int id)
    {
 
        // 'this' keyword refers to current object itself
        this.id = id;
    }
 
    // Converting the above Integer variable to String
    public String toString()
    {
        return "Student[" + this.id + "]";
    }
 
    // Getting the 'id'
    public int getId() { return this.id; }
 
    // Comparing the ids ot two student
    // using the compareTo() method
    public int compareTo(Student otherStudent)
    {
        return this.getId() - otherStudent.getId();
    }
}
 
// Class 2
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of Vector type
        // Declaring object of Student(user-defined type)
        Vector student = new Vector<>();
 
        // Adding student id to vector
        // Custom input elements
        student.add(new Student(1));
        student.add(new Student(2));
        student.add(new Student(9));
        student.add(new Student(4));
        student.add(new Student(34));
 
        // Print all the elements
        // before sorting
        System.out.println(student);
 
        // Calling sort() method of collections
        Collections.sort(student);
 
        // Print all the elements
        // after sorting
        System.out.println(student);
    }
}


Java
// Java Program to Sort Vector Elements
// using Comparable Interface
 
// Importing Collection an Vector classes from
// java.util package
import java.util.Collections;
import java.util.Vector;
import java.util.*;
 
// Class 1
// Helper class
// Class implementing comparable interface
class Student implements Comparable {
 
// // Declaring a variables- student name , marks and id
String name;
int marks;
int id;
 
// Initializing the above variable through
// self constructor of this class
public Student(String name,int marks,int id) {
 
  // 'this' keyword refers to current object itself 
  this.name=name;
  this.marks=marks;
  this.id=id;
  }
 
// Getting the 'id'
public int getMarks(){
 return this.marks;
 }
 
// Comparing the ids ot two student
// using the compareTo() method
public int compareTo(Student otherStudent) {
 
  return this.getMarks()-otherStudent.getMarks();
  }
 
}
 
// Class 2
// Main class
class GFG {
 
// Main driver method
public static void main(String[] args) {
 
// Creating an object of Vector type
// Declaring object of Student(user-defined type)
Vector student= new Vector<>();
 
// Adding student id to vector
// Custom input elements
student.add(new Student("Roshan",86,1));
student.add(new Student("Ritik",96,2));
student.add(new Student("Ashish",99,4));
student.add(new Student("Sandeep",100,9));
student.add(new Student("Piyush",88,34));
 
// Iterate over the sorted vector
// using for each loop
// before calling sort() method
for(Student s : student)
 
// Print and display the sorted vector
System.out.println("Name:"+s.name +"->"+"Marks:"+s.marks+"->"+"ID:"+s.id);
 
// New line
System.out.println() ;
 
// Calling sort() method of collections
Collections.sort(student);
 
// Iterate over the sorted vector
// using for each loop
// after calling sort() method
for(Student s : student)
 
// Print and display the sorted vector
System.out.println("Name:"+s.name +"->"+"Marks:"+s.marks+"->"+"ID:"+s.id);
 
}
 
}


输出
[Student[1], Student[2], Student[9], Student[4], Student[34]]
[Student[1], Student[2], Student[4], Student[9], Student[34]]

示例 2:学生姓名、分数和 id,我们将根据学生分数对向量进行排序

Java

// Java Program to Sort Vector Elements
// using Comparable Interface
 
// Importing Collection an Vector classes from
// java.util package
import java.util.Collections;
import java.util.Vector;
import java.util.*;
 
// Class 1
// Helper class
// Class implementing comparable interface
class Student implements Comparable {
 
// // Declaring a variables- student name , marks and id
String name;
int marks;
int id;
 
// Initializing the above variable through
// self constructor of this class
public Student(String name,int marks,int id) {
 
  // 'this' keyword refers to current object itself 
  this.name=name;
  this.marks=marks;
  this.id=id;
  }
 
// Getting the 'id'
public int getMarks(){
 return this.marks;
 }
 
// Comparing the ids ot two student
// using the compareTo() method
public int compareTo(Student otherStudent) {
 
  return this.getMarks()-otherStudent.getMarks();
  }
 
}
 
// Class 2
// Main class
class GFG {
 
// Main driver method
public static void main(String[] args) {
 
// Creating an object of Vector type
// Declaring object of Student(user-defined type)
Vector student= new Vector<>();
 
// Adding student id to vector
// Custom input elements
student.add(new Student("Roshan",86,1));
student.add(new Student("Ritik",96,2));
student.add(new Student("Ashish",99,4));
student.add(new Student("Sandeep",100,9));
student.add(new Student("Piyush",88,34));
 
// Iterate over the sorted vector
// using for each loop
// before calling sort() method
for(Student s : student)
 
// Print and display the sorted vector
System.out.println("Name:"+s.name +"->"+"Marks:"+s.marks+"->"+"ID:"+s.id);
 
// New line
System.out.println() ;
 
// Calling sort() method of collections
Collections.sort(student);
 
// Iterate over the sorted vector
// using for each loop
// after calling sort() method
for(Student s : student)
 
// Print and display the sorted vector
System.out.println("Name:"+s.name +"->"+"Marks:"+s.marks+"->"+"ID:"+s.id);
 
}
 
}
输出
Name:Roshan->Marks:86->ID:1
Name:Ritik->Marks:96->ID:2
Name:Ashish->Marks:99->ID:4
Name:Sandeep->Marks:100->ID:9
Name:Piyush->Marks:88->ID:34

Name:Roshan->Marks:86->ID:1
Name:Piyush->Marks:88->ID:34
Name:Ritik->Marks:96->ID:2
Name:Ashish->Marks:99->ID:4
Name:Sandeep->Marks:100->ID:9