📜  如何在Java中使用 Comparable 接口创建 TreeMap 对象?

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

如何在Java中使用 Comparable 接口创建 TreeMap 对象?

在Java.lang 包中找到了可比较的接口,它用于仅根据单个属性对用户定义的类的对象进行排序。该接口包含一个方法 compareTo(Object)。它用于当前对象与指定对象进行比较,并可用于对用户定义的类包装类和字符串对象进行排序。

句法:

compareTo(Object o) ;

参数:与当前对象进行比较的指定对象。

返回类型:整数值

  • 正整数 — 如果当前对象大于指定对象。
  • 负整数 — 如果当前对象小于指定对象。
  • 零 — 如果当前对象等于指定对象。

Java中可比较接口的使用

Java中的 TreeMap ,元素存储为键值对,并根据键进行排序。当Key为String类或Wrapper Classes时,默认实现Comparable接口,按排序顺序存储元素。但是,如果有人想要制作特定用户定义类型(即用户定义类)的所需键,我们需要实现 Comparable 接口以基于属性以特定顺序对对象进行排序。

实现:不使用可比较的接口。

Java
// Creating TreeMap objects using
// Comparable interface in Java
 
// Importing all generic java utility and input
import java.io.*;
import java.util.*;
 
// Class - User defined named Employee
public class Employee {
 
    // Attributes of object of class
    int id;
    String name;
 
    // Parameterized constructor for user-defined class
    public Employee(int id, String name)
    {
        // This keyword refers to current object in a
        // constructor
        this.id = id;
        this.name = name;
    }
}
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args) throws Exception
    {
        // Declaring and initializing a TreeMap
        TreeMap tm = new TreeMap<>();
 
        // Employee object1
        // custom input
        Employee e1 = new Employee(1, "Pathak");
 
        // Employee object2
        // custom input
        Employee e2 = new Employee(2, "Anshu");
 
        // Put method associating specific key-value in Map
        tm.put(e1, "First");
        tm.put(e2, "Second");
 
        // Iterating over Map using for-each loop
        // Map with employee Key
        for (Map.Entry e :
             tm.entrySet()) {
 
            // Print key-value pairs of TreeMap
            System.out.println(e.getKey().id + " "
                               + e.getValue());
        }
    }
}


Java
// Creating TreeMap objects using
// Comparable interface in Java
 
// Importing all generic java utility and input
import java.io.*;
import java.util.*;
 
// User-defined class named Employee
// implementing comparable
public class Employee implements Comparable {
 
    // Attributes of object of class
    int id;
    String name;
 
    // Parameterized constructor for user-defined class
    public Employee(int id, String name)
    {
        // This keyword refers to
        // current object in a constructor
        this.id = id;
        this.name = name;
    }
 
    // Comparable interface
    public int compareTo(Employee e)
    {
        // Two instance of class can be compared
        int diff = this.id - e.id;
 
        // Note: Two equal employee Id will return 0
        return diff;
    }
}
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Declaring and initializing a TreeMap
        TreeMap tm = new TreeMap<>();
 
        // Employee object1 (custom input)
        Employee e1 = new Employee(1, "Pathak");
 
        // Employee object2 (custom input)
        Employee e2 = new Employee(2, "Anshu");
 
        // Put method associating specific key-value in Map
        tm.put(e1, "First");
        tm.put(e2, "Second");
 
        // Iterating over Map using for-each loop
        // Map with employee key
        for (Map.Entry e :
             tm.entrySet()) {
 
            // Print key-value pairs of TreeMap
            System.out.println(e.getKey().id + " "
                               + e.getKey().name + " "
                               + e.getValue());
        }
    }
}


输出:错误

上面的代码抛出异常,因为没有实现可比较的接口,因此它不能以正确的顺序基于键对地图元素进行排序。所以,为了处理异常

实现:使用可比较的接口。

Java

// Creating TreeMap objects using
// Comparable interface in Java
 
// Importing all generic java utility and input
import java.io.*;
import java.util.*;
 
// User-defined class named Employee
// implementing comparable
public class Employee implements Comparable {
 
    // Attributes of object of class
    int id;
    String name;
 
    // Parameterized constructor for user-defined class
    public Employee(int id, String name)
    {
        // This keyword refers to
        // current object in a constructor
        this.id = id;
        this.name = name;
    }
 
    // Comparable interface
    public int compareTo(Employee e)
    {
        // Two instance of class can be compared
        int diff = this.id - e.id;
 
        // Note: Two equal employee Id will return 0
        return diff;
    }
}
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Declaring and initializing a TreeMap
        TreeMap tm = new TreeMap<>();
 
        // Employee object1 (custom input)
        Employee e1 = new Employee(1, "Pathak");
 
        // Employee object2 (custom input)
        Employee e2 = new Employee(2, "Anshu");
 
        // Put method associating specific key-value in Map
        tm.put(e1, "First");
        tm.put(e2, "Second");
 
        // Iterating over Map using for-each loop
        // Map with employee key
        for (Map.Entry e :
             tm.entrySet()) {
 
            // Print key-value pairs of TreeMap
            System.out.println(e.getKey().id + " "
                               + e.getKey().name + " "
                               + e.getValue());
        }
    }
}


输出
1 Pathak First
2 Anshu Second