众所周知,在使用TreeSet时,我们需要实现Comparable接口并添加compareTo()。不这样做将会抛出 ClassCastException。现在我有一个 TreeSet,我需要添加 ArrayList 作为 TreeSet 的元素。
如果我们写:
ArrayList al = new ArrayList();
ArrayList al2 = new ArrayList();
ArrayList al3 = new ArrayList();
TreeSet ts = new TreeSet();
ts.add(al);
ts.add(al2);
ts.add(al3);
Run Code Online (Sandbox Code Playgroud)
它抛出 ClassCastException。
问题:如何将 ArrayList 实例(而不是其元素)添加到 TreeSet 或 TreeMap?
我希望按照电子邮件地址的顺序对我的对象进行排序。
这是我尝试过的方法,但它不起作用,但我什至不确定这是做我想做的事情的正确方法吗?
public static ArrayList<Billing> sortedListByEmail(ArrayList<Billing> Billing) {
ArrayList<Billing> Sort = new ArrayList<Billing>();
for (int i = 0; i < Sort.size(); i++) {
Collections.sort(Sort, new Comparator<Billing>() {
public int compare(Billing o1, Billing o2) {
return o1.getEmail() > o2.getEmail() ? -1 : o1.getEmail().equals(o2.getEmail() ? 0 : 1);
}
});
}
return Sort;
}
Run Code Online (Sandbox Code Playgroud)
其余班级:
import java.util.ArrayList;
import java.util.Collections;
import java.lang.Comparable;
import java.util.Comparator;
public class Billing extends User implements Comparable<User> {
private Address billingAddress;
private String email;
public Billing(String id, String firstName, …Run Code Online (Sandbox Code Playgroud) 我正在查看 Java 的 TheAlgorithms 存储库,首先找到了这个: https: //github.com/TheAlgorithms/Java/blob/master/Searches/SearchAlgorithm.java。我明白了<T extends Comparable<T>>,但我不知道这意味着什么。我只了解一点关于泛型的知识,并且我知道语法与参数类型边界有关,但是如果有人能够澄清这与Comparable<T>和 是什么Comparable<T>有什么关系,那就太好了。
这个论坛上还有一些与我的类似的其他问题,涉及实施<T extends Comparable<T>>,但答案并没有真正澄清是什么Comparable<T>。
我目前在理解Comparable 类的compareTo 方法如何工作以及如何重写它方面遇到一些困难。我有成对的数组,每个对都包含 2 个双精度值,我正在尝试对其进行排序。这是我尝试过的:
static class Pair implements Comparable<Pair>
{
double x;
double y;
Pair(double x, double y)
{
this.x = x;
this.y = y;
}
public double compareTo(Pair other)
{
return y - other.y;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,它无法编译,而是给我这个错误:
Main.java:5: error: Pair is not abstract and does not override abstract method compareTo(Pair) in Comparable
static class Pair implements Comparable<Pair>
^
Main.java:14: error: compareTo(Pair) in Pair cannot implement compareTo(T) in Comparable
public double compareTo(Pair other)
^
return type double is not …Run Code Online (Sandbox Code Playgroud) 我有这个类存储坐标的纬度和经度以及距中心的距离。在我的算法中的某个时刻,我有一个这些坐标的列表,我想按它们距中心的距离对它们进行排序。因此,我实现了Comparable接口及其compareTo方法。
public class Coordinate implements Comparable<Coordinate> {
private Double lat;
private Double lon;
private Double distanceCenter;
protected Coordinate(Double lon, Double lat, Double distanceFromCenter) {
this.lat=lat;
this.lon=lon;
this.distanceCenter=distanceFromCenter;
}
public Double getDistanceFromCenter() {
return distanceFromCenter;
}
@Override
public int compareTo(Coordinate compared) {
return (int) ((this.distanceCenter) - (compared.getDistanceCenter()));
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,有时两点之间的差异太小(几乎为零),java会抛出一个
java.lang.IllegalArgumentException: Comparison method violates its general contract
Run Code Online (Sandbox Code Playgroud)
我解决了这个问题,只需将每个距离乘以一个非常大的数字,以避免任何“重要性损失”效应
@Override
public int compareTo(Eq compared) {
return (int) ((this.distanceCenter*1000000000000000.0) (compared.getDistanceCenter()*1000000000000000.0));
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有更优雅的方法来解决此类问题或者我是否做错了什么
我Student使用 java 8 的自然排序方法迭代所有数据sorted()。迭代学生数据时,在 IDE 控制台中出现异常class com.java8.Student cannot be cast to class java.lang.Comparable。我的StreamStudent.java文件在com.java8包内。
这是我的完整堆栈跟踪:
Exception in thread "main" java.lang.ClassCastException: class com.java8.Student cannot be cast to class java.lang.Comparable (com.java8.Student is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
at java.base/java.util.Comparators$NaturalOrderComparator.compare(Comparators.java:47)
at java.base/java.util.TimSort.countRunAndMakeAscending(TimSort.java:355)
at java.base/java.util.TimSort.sort(TimSort.java:220)
at java.base/java.util.Arrays.sort(Arrays.java:1307)
at java.base/java.util.stream.SortedOps$SizedRefSortingSink.end(SortedOps.java:353)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:510)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:921)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682)
at com.java8.StreamStudent.main(StreamStudent.java:72)
Run Code Online (Sandbox Code Playgroud)
下面是我的代码:
package com.java8;
import java.util.*; …Run Code Online (Sandbox Code Playgroud) 假设我有一个名为RandomObject:
public class RandomObject implements Comparable<RandomObject> {
private String name;
private int value;
public RandomObject(String name, int value) {
this.name = name;
this.value = value;
}
.
.
.
public int compareTo(RandomObject rn) {
return Integer.compare(value, rn.value);
}
Run Code Online (Sandbox Code Playgroud)
这个RandomObjects 数组(每个数组都保存一个随机 int 值,用于比较目的):
RandomObject[] arr = new RandomObject[10];
for (int i = 0; i < arr.length; ++i) {
arr[i] = new RandomObject(" ", (int) (Math.random() * 50));
}
Run Code Online (Sandbox Code Playgroud)
我还有一个名为Quicksort包含以下排序方法的类:
public static <T extends Comparable<? super …Run Code Online (Sandbox Code Playgroud) 我有这个嵌套数组:
[[1, 2, 3],
[1, 3, 6],
[1, 4, 12],
[1, 5, 5],
[1, 2, 3],
[1, 8, 7],
[2, 3, 3],
[2, 4, 9],
[2, 5, 2],
[2, 8, 4],
[3, 4, 6],
[3, 8, 1],
[5, 8, 2],
[2, 8, 4],
[7, 8, 9]]
Run Code Online (Sandbox Code Playgroud)
我试图找到一种简洁但可读的方式:
我尝试过各种方法,例如,,,,但没有成功#max,#max_by但#group_by我#with_index现在正处于这样一个阶段,我可以从比我更有能力的大脑和程序员那里得到一些启发。
所以基本上我有这样的事情:
private SortedDictionary<Priority, List<String>> example = new SortedDictionary<Priority, List<String>>(new PriorityComparer());
public void Submit(Priority priority, String test)
{
if (!example.ContainsKey(priority))
{
example.Add(priority, new List<String> { test });
// adds an entry with the key (Priority.Low) twice, why?
}
else
{
example[priority].Add(test); // never called
}
}
Run Code Online (Sandbox Code Playgroud)
只需提交一堆测试元素:
Submit(Priority.Critical, "test4");
Submit(Priority.Low, "test");
Submit(Priority.Normal, "test3");
Submit(Priority.Low, "test2");
Run Code Online (Sandbox Code Playgroud)
优先级只是一个枚举,优先级从低(0)到严重(10).这只是一个典型的枚举,没什么特别的.
优先比较器:
public class PriorityComparer : IComparer<Priority>
{
public int Compare(Priority x, Priority y)
{
if (x > y)
{
return -1;
}
else
{
return …Run Code Online (Sandbox Code Playgroud) 我一直在浏览Comparable vs Comparator接口的实现示例.
但是,我一直坚持在它的实施中:
假设,我有一个简单的类:Employee,它具有基于员工姓名的默认排序机制.
public class Employee implements Comparable<Employee> {
private int empSalary;
private String empName;
@Override
public int compareTo(Employee e) {
return this.empName.compareTo(e.empName);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,让我们说,我首先要根据员工姓名排序,然后如果两个员工有相同的名字,我就要根据他们的工资对他们进行排序.
所以,我写了一个自定义比较器,根据下面的工资进行排序
public class SalaryComparator implements Comparator<Employee> {
@Override
public int compare(Employee e1, Employee e2) {
return e1.empSalary - e2.empSalary;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行我的测试类时,首先根据名称进行排序,然后是第二个工资,输出不是预期的.
Collections.sort(employeeList, new SalaryComparator());
Run Code Online (Sandbox Code Playgroud)
输入订单:
Name : Kumar, Salary : 40
Name : Sanket, Salary : 10
Name : Kumar, Salary : 20
Run Code Online (Sandbox Code Playgroud)
预期产量:
Name : Kumar, Salary : 20
Name …Run Code Online (Sandbox Code Playgroud) comparable ×10
java ×8
sorting ×3
collections ×2
compareto ×2
dictionary ×2
generics ×2
arraylist ×1
c# ×1
comparator ×1
double ×1
enumerable ×1
enums ×1
java-8 ×1
java-stream ×1
ruby ×1
set ×1
types ×1