我学会了如何使用可比较的但是我对比较器有困难。我的代码中有错误:
Exception in thread "main" java.lang.ClassCastException: New.People cannot be cast to java.lang.Comparable
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at New.TestPeople.main(TestPeople.java:18)
这是我的代码:
import java.util.Comparator;
public class People implements Comparator {
private int id;
private String info;
private double price;
public People(int newid, String newinfo, double newprice) {
setid(newid);
setinfo(newinfo);
setprice(newprice);
}
public int getid() {
return id;
}
public void setid(int id) {
this.id = id;
}
public String getinfo() {
return info;
}
public void setinfo(String info) {
this.info = info;
}
public double getprice() {
return price;
}
public void setprice(double price) {
this.price = price;
}
public int compare(Object obj1, Object obj2) {
Integer p1 = ((People) obj1).getid();
Integer p2 = ((People) obj2).getid();
if (p1 > p2) {
return 1;
} else if (p1 < p2){
return -1;
} else {
return 0;
}
}
}
import java.util.ArrayList;
import java.util.Collections;
public class TestPeople {
public static void main(String[] args) {
ArrayList peps = new ArrayList();
peps.add(new People(123, "M", 14.25));
peps.add(new People(234, "M", 6.21));
peps.add(new People(362, "F", 9.23));
peps.add(new People(111, "M", 65.99));
peps.add(new People(535, "F", 9.23));
Collections.sort(peps);
for (int i = 0; i < peps.size(); i++){
System.out.println(peps.get(i));
}
}
}
我相信它必须在比较方法中使用铸造做一些事情,但我正在玩它仍然无法找到解决方案
答案 0 :(得分:200)
您的示例类有一些尴尬的事情:
price
和info
(对象更多的东西,而不是人物); 无论如何,这是一个如何使用Comparator<T>
:
public class ComparatorDemo {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Joe", 24),
new Person("Pete", 18),
new Person("Chris", 21)
);
Collections.sort(people, new LexicographicComparator());
System.out.println(people);
Collections.sort(people, new AgeComparator());
System.out.println(people);
}
}
class LexicographicComparator implements Comparator<Person> {
@Override
public int compare(Person a, Person b) {
return a.name.compareToIgnoreCase(b.name);
}
}
class AgeComparator implements Comparator<Person> {
@Override
public int compare(Person a, Person b) {
return a.age < b.age ? -1 : a.age == b.age ? 0 : 1;
}
}
class Person {
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
@Override
public String toString() {
return String.format("{name=%s, age=%d}", name, age);
}
}
等效的Java 8演示如下所示:
public class ComparatorDemo {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Joe", 24),
new Person("Pete", 18),
new Person("Chris", 21)
);
Collections.sort(people, (a, b) -> a.name.compareToIgnoreCase(b.name));
System.out.println(people);
Collections.sort(people, (a, b) -> a.age < b.age ? -1 : a.age == b.age ? 0 : 1);
System.out.println(people);
}
}
答案 1 :(得分:139)
这是一个超短的模板,可以立即进行排序:
Collections.sort(people,new Comparator<Person>(){
@Override
public int compare(final Person lhs,Person rhs) {
//TODO return 1 if rhs should be before lhs
// return -1 if lhs should be before rhs
// return 0 otherwise (meaning the order stays the same)
}
});
如果难以记住,请尽量记住它(在数字符号方面)类似于:
lhs-rhs
如果你想按升序排序:从最小的数字到最大的数字。
答案 2 :(得分:33)
改用People implements Comparable<People>
;这定义了People
的自然顺序。
此外,还可以定义Comparator<People>
,但People implements Comparator<People>
不是正确的做事方式。
Collections.sort
的两个重载是不同的:
<T extends Comparable<? super T>> void sort(List<T> list)
Comparable
个对象进行排序<T> void sort(List<T> list, Comparator<? super T> c)
Comparator
你通过尝试对Comparator
进行排序来混淆两者(这也是为什么Person implements Comparator<Person>
没有意义的原因)。同样,要使用Collections.sort
,您需要其中一个为真:
Comparable
(使用1-arg sort
)Comparator
(使用2-args sort
)此外,不要在新代码中使用原始类型。原始类型是不安全的,并且仅提供兼容性。
即代替:
ArrayList peps = new ArrayList(); // BAD!!! No generic safety!
你应该使用这样的类型安全通用声明:
List<People> peps = new ArrayList<People>(); // GOOD!!!
然后您会发现您的代码甚至无法编译!! 这将是一件好事,因为代码有问题(Person
没有{{1 }},但是因为你使用了原始类型,编译器没有检查这个,而是在运行时得到implements Comparable<Person>
!!!
这应该说服您始终在新代码中使用类型安全泛型类型。总是
答案 3 :(得分:11)
为了完整起见,这是一个简单的单行compare
方法:
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person lhs, Person rhs) {
return Integer.signum(lhs.getId() - rhs.getId());
}
});
答案 4 :(得分:9)
Java 8增加了一种制作比较器的新方法,可以减少您必须编写的代码量Comparator.comparing。另请查看Comparator.reversed
这是一个示例
import org.junit.Test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import static org.junit.Assert.assertTrue;
public class ComparatorTest {
@Test
public void test() {
List<Person> peopleList = new ArrayList<>();
peopleList.add(new Person("A", 1000));
peopleList.add(new Person("B", 1));
peopleList.add(new Person("C", 50));
peopleList.add(new Person("Z", 500));
//sort by name, ascending
peopleList.sort(Comparator.comparing(Person::getName));
assertTrue(peopleList.get(0).getName().equals("A"));
assertTrue(peopleList.get(peopleList.size() - 1).getName().equals("Z"));
//sort by name, descending
peopleList.sort(Comparator.comparing(Person::getName).reversed());
assertTrue(peopleList.get(0).getName().equals("Z"));
assertTrue(peopleList.get(peopleList.size() - 1).getName().equals("A"));
//sort by age, ascending
peopleList.sort(Comparator.comparing(Person::getAge));
assertTrue(peopleList.get(0).getAge() == 1);
assertTrue(peopleList.get(peopleList.size() - 1).getAge() == 1000);
//sort by age, descending
peopleList.sort(Comparator.comparing(Person::getAge).reversed());
assertTrue(peopleList.get(0).getAge() == 1000);
assertTrue(peopleList.get(peopleList.size() - 1).getAge() == 1);
}
class Person {
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
}
答案 5 :(得分:4)
您想要实现Comparable,而不是Comparator。您需要实现compareTo方法。你虽然很近。比较器是“第三方”比较例程。可比较的是,这个对象可以与另一个对象进行比较。
public int compareTo(Object obj1) {
People that = (People)obj1;
Integer p1 = this.getId();
Integer p2 = that.getid();
if (p1 > p2 ){
return 1;
}
else if (p1 < p2){
return -1;
}
else
return 0;
}
注意,你可能想在这里检查getId..just中的空值。
答案 6 :(得分:2)
这是一个比较器的示例,它将适用于返回Comparable的任何零arg方法。在jdk或库中是否存在这样的东西?
import java.lang.reflect.Method;
import java.util.Comparator;
public class NamedMethodComparator implements Comparator<Object> {
//
// instance variables
//
private String methodName;
private boolean isAsc;
//
// constructor
//
public NamedMethodComparator(String methodName, boolean isAsc) {
this.methodName = methodName;
this.isAsc = isAsc;
}
/**
* Method to compare two objects using the method named in the constructor.
*/
@Override
public int compare(Object obj1, Object obj2) {
Comparable comp1 = getValue(obj1, methodName);
Comparable comp2 = getValue(obj2, methodName);
if (isAsc) {
return comp1.compareTo(comp2);
} else {
return comp2.compareTo(comp1);
}
}
//
// implementation
//
private Comparable getValue(Object obj, String methodName) {
Method method = getMethod(obj, methodName);
Comparable comp = getValue(obj, method);
return comp;
}
private Method getMethod(Object obj, String methodName) {
try {
Class[] signature = {};
Method method = obj.getClass().getMethod(methodName, signature);
return method;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
private Comparable getValue(Object obj, Method method) {
Object[] args = {};
try {
Object rtn = method.invoke(obj, args);
Comparable comp = (Comparable) rtn;
return comp;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
}
答案 7 :(得分:1)
public static Comparator<JobSet> JobEndTimeComparator = new Comparator<JobSet>() {
public int compare(JobSet j1, JobSet j2) {
int cost1 = j1.cost;
int cost2 = j2.cost;
return cost1-cost2;
}
};
答案 8 :(得分:1)
可以通过以下方式优化解决方案: 首先,使用私有内部类,因为字段的范围是封闭类TestPeople,因此类的实现将不会暴露给外部世界。这可以通过创建期望排序的人员列表的API来理解 其次,使用Lamba表达式(java 8)减少代码,从而减少开发工作量
因此代码如下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class TestPeople {
public static void main(String[] args) {
ArrayList<People> peps = new ArrayList<>();// Be specific, to avoid
// classCast Exception
TestPeople test = new TestPeople();
peps.add(test.new People(123, "M", 14.25));
peps.add(test.new People(234, "M", 6.21));
peps.add(test.new People(362, "F", 9.23));
peps.add(test.new People(111, "M", 65.99));
peps.add(test.new People(535, "F", 9.23));
/*
* Collections.sort(peps);
*
* for (int i = 0; i < peps.size(); i++){
* System.out.println(peps.get(i)); }
*/
// The above code can be replaced by followin:
peps.sort((People p1, People p2) -> p1.getid() - p2.getid());
peps.forEach((p) -> System.out.println(" " + p.toString()));
}
private class People {
private int id;
@Override
public String toString() {
return "People [id=" + id + ", info=" + info + ", price=" + price + "]";
}
private String info;
private double price;
public People(int newid, String newinfo, double newprice) {
setid(newid);
setinfo(newinfo);
setprice(newprice);
}
public int getid() {
return id;
}
public void setid(int id) {
this.id = id;
}
public String getinfo() {
return info;
}
public void setinfo(String info) {
this.info = info;
}
public double getprice() {
return price;
}
public void setprice(double price) {
this.price = price;
}
}
}
答案 9 :(得分:0)
您应该使用重载排序(peps,new People())方法
<cfoutput>#request.rootPath#</cfoutput>
答案 10 :(得分:0)
Two corrections:
首先,您必须创建一个People对象的ArrayList:
ArrayList<People> preps= new ArrayList<People>();
然后将对象添加到准备中,使用:
Collections.sort(preps,new CompareId());
还要添加一个CompareId类:
class CompareId implements Comparator{
public int compare(Object obj1,Object obj2){
People t1=(People)obj1;
People t2=(People)obj2;
if(t1.marks>t2.marks)
return 1;
else
return -1;
}
}
答案 11 :(得分:0)
这是我对简单比较器工具的回答
public class Comparator {
public boolean isComparatorRunning = false;
public void compareTableColumns(List<String> tableNames) {
if(!isComparatorRunning) {
isComparatorRunning = true;
try {
for (String schTableName : tableNames) {
Map<String, String> schemaTableMap = ComparatorUtil.getSchemaTableMap(schTableName);
Map<String, ColumnInfo> primaryColMap = ComparatorUtil.getColumnMetadataMap(DbConnectionRepository.getConnectionOne(), schemaTableMap);
Map<String, ColumnInfo> secondaryColMap = ComparatorUtil.getColumnMetadataMap(DbConnectionRepository.getConnectionTwo(), schemaTableMap);
ComparatorUtil.publishColumnInfoOutput("Comparing table : "+ schemaTableMap.get(CompConstants.TABLE_NAME));
compareColumns(primaryColMap, secondaryColMap);
}
} catch (Exception e) {
ComparatorUtil.publishColumnInfoOutput("ERROR"+e.getMessage());
}
isComparatorRunning = false;
}
}
public void compareColumns(Map<String, ColumnInfo> primaryColMap, Map<String, ColumnInfo> secondaryColMap) {
try {
boolean isEqual = true;
for(Map.Entry<String, ColumnInfo> entry : primaryColMap.entrySet()) {
String columnName = entry.getKey();
ColumnInfo primaryColInfo = entry.getValue();
ColumnInfo secondaryColInfo = secondaryColMap.remove(columnName);
if(secondaryColInfo == null) {
// column is not present in Secondary Environment
ComparatorUtil.publishColumnInfoOutput("ALTER", primaryColInfo);
isEqual = false;
continue;
}
if(!primaryColInfo.equals(secondaryColInfo)) {
isEqual = false;
// Column not equal in secondary env
ComparatorUtil.publishColumnInfoOutput("MODIFY", primaryColInfo);
}
}
if(!secondaryColMap.isEmpty()) {
isEqual = false;
for(Map.Entry<String, ColumnInfo> entry : secondaryColMap.entrySet()) {
// column is not present in Primary Environment
ComparatorUtil.publishColumnInfoOutput("DROP", entry.getValue());
}
}
if(isEqual) {
ComparatorUtil.publishColumnInfoOutput("--Exact Match");
}
} catch (Exception e) {
ComparatorUtil.publishColumnInfoOutput("ERROR"+e.getMessage());
}
}
public void compareTableColumnsValues(String primaryTableName, String primaryColumnNames, String primaryCondition, String primaryKeyColumn,
String secTableName, String secColumnNames, String secCondition, String secKeyColumn) {
if(!isComparatorRunning) {
isComparatorRunning = true;
Connection conn1 = DbConnectionRepository.getConnectionOne();
Connection conn2 = DbConnectionRepository.getConnectionTwo();
String query1 = buildQuery(primaryTableName, primaryColumnNames, primaryCondition, primaryKeyColumn);
String query2 = buildQuery(secTableName, secColumnNames, secCondition, secKeyColumn);
try {
Map<String,Map<String, Object>> query1Data = executeAndRefactorData(conn1, query1, primaryKeyColumn);
Map<String,Map<String, Object>> query2Data = executeAndRefactorData(conn2, query2, secKeyColumn);
for(Map.Entry<String,Map<String, Object>> entry : query1Data.entrySet()) {
String key = entry.getKey();
Map<String, Object> value = entry.getValue();
Map<String, Object> secondaryValue = query2Data.remove(key);
if(secondaryValue == null) {
ComparatorUtil.publishColumnValuesInfoOutput("NO SUCH VALUE AVAILABLE IN SECONDARY DB "+ value.toString());
continue;
}
compareMap(value, secondaryValue, key);
}
if(!query2Data.isEmpty()) {
ComparatorUtil.publishColumnValuesInfoOutput("Extra Values in Secondary table "+ ((Map)query2Data.values()).values().toString());
}
} catch (Exception e) {
ComparatorUtil.publishColumnValuesInfoOutput("ERROR"+e.getMessage());
}
isComparatorRunning = false;
}
}
private void compareMap(Map<String, Object> primaryValues, Map<String, Object> secondaryValues, String columnIdentification) {
for(Map.Entry<String, Object> entry : primaryValues.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
Object secValue = secondaryValues.get(key);
if(value!=null && secValue!=null && !String.valueOf(value).equalsIgnoreCase(String.valueOf(secValue))) {
ComparatorUtil.publishColumnValuesInfoOutput(columnIdentification+" : Secondary Table does not match value ("+ value +") for column ("+ key+")");
}
if(value==null && secValue!=null) {
ComparatorUtil.publishColumnValuesInfoOutput(columnIdentification+" : Values not available in primary table for column "+ key);
}
if(value!=null && secValue==null) {
ComparatorUtil.publishColumnValuesInfoOutput(columnIdentification+" : Values not available in Secondary table for column "+ key);
}
}
}
private String buildQuery(String tableName, String column, String condition, String keyCol) {
if(!"*".equalsIgnoreCase(column)) {
String[] keyColArr = keyCol.split(",");
for(String key: keyColArr) {
if(!column.contains(key.trim())) {
column+=","+key.trim();
}
}
}
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append("select "+column+" from "+ tableName);
if(!ComparatorUtil.isNullorEmpty(condition)) {
queryBuilder.append(" where 1=1 and "+condition);
}
return queryBuilder.toString();
}
private Map<String,Map<String, Object>> executeAndRefactorData(Connection connection, String query, String keyColumn) {
Map<String,Map<String, Object>> result = new HashMap<String, Map<String,Object>>();
try {
PreparedStatement preparedStatement = connection.prepareStatement(query);
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.setFetchSize(1000);
if (resultSet != null && !resultSet.isClosed()) {
while (resultSet.next()) {
Map<String, Object> columnValueDetails = new HashMap<String, Object>();
int columnCount = resultSet.getMetaData().getColumnCount();
for (int i=1; i<=columnCount; i++) {
String columnName = String.valueOf(resultSet.getMetaData().getColumnName(i));
Object columnValue = resultSet.getObject(columnName);
columnValueDetails.put(columnName, columnValue);
}
String[] keys = keyColumn.split(",");
String newKey = "";
for(int j=0; j<keys.length; j++) {
newKey += String.valueOf(columnValueDetails.get(keys[j]));
}
result.put(newKey , columnValueDetails);
}
}
} catch (SQLException e) {
ComparatorUtil.publishColumnValuesInfoOutput("ERROR"+e.getMessage());
}
return result;
}
}
相同的实用工具
public class ComparatorUtil {
public static Map<String, String> getSchemaTableMap(String tableNameWithSchema) {
if(isNullorEmpty(tableNameWithSchema)) {
return null;
}
Map<String, String> result = new LinkedHashMap<>();
int index = tableNameWithSchema.indexOf(".");
String schemaName = tableNameWithSchema.substring(0, index);
String tableName = tableNameWithSchema.substring(index+1);
result.put(CompConstants.SCHEMA_NAME, schemaName);
result.put(CompConstants.TABLE_NAME, tableName);
return result;
}
public static Map<String, ColumnInfo> getColumnMetadataMap(Connection conn, Map<String, String> schemaTableMap) {
try {
String schemaName = schemaTableMap.get(CompConstants.SCHEMA_NAME);
String tableName = schemaTableMap.get(CompConstants.TABLE_NAME);
ResultSet resultSetConnOne = conn.getMetaData().getColumns(null, schemaName, tableName, null);
Map<String, ColumnInfo> resultSetTwoColInfo = getColumnInfo(schemaName, tableName, resultSetConnOne);
return resultSetTwoColInfo;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/* Number Type mapping
* 12-----VARCHAR
* 3-----DECIMAL
* 93-----TIMESTAMP
* 1111-----OTHER
*/
public static Map<String, ColumnInfo> getColumnInfo(String schemaName, String tableName, ResultSet columns) {
try {
Map<String, ColumnInfo> tableColumnInfo = new LinkedHashMap<String, ColumnInfo>();
while (columns.next()) {
ColumnInfo columnInfo = new ColumnInfo();
columnInfo.setSchemaName(schemaName);
columnInfo.setTableName(tableName);
columnInfo.setColumnName(columns.getString("COLUMN_NAME"));
columnInfo.setDatatype(columns.getString("DATA_TYPE"));
columnInfo.setColumnsize(columns.getString("COLUMN_SIZE"));
columnInfo.setDecimaldigits(columns.getString("DECIMAL_DIGITS"));
columnInfo.setIsNullable(columns.getString("IS_NULLABLE"));
tableColumnInfo.put(columnInfo.getColumnName(), columnInfo);
}
return tableColumnInfo;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static boolean isNullOrEmpty(Object obj) {
if (obj == null)
return true;
if (String.valueOf(obj).equalsIgnoreCase("NULL"))
return true;
if (obj.toString().trim().length() == 0)
return true;
return false;
}
public static boolean isNullorEmpty(String str) {
if(str == null)
return true;
if(str.trim().length() == 0)
return true;
return false;
}
public static void publishColumnInfoOutput(String type, ColumnInfo columnInfo) {
String str = "ALTER TABLE "+columnInfo.getSchemaName()+"."+columnInfo.getTableName();
switch(type.toUpperCase()) {
case "ALTER":
if("NUMBER".equalsIgnoreCase(columnInfo.getDatatype()) || "DATE".equalsIgnoreCase(columnInfo.getDatatype())) {
str += " ADD ("+columnInfo.getColumnName()+" "+ columnInfo.getDatatype()+");";
} else {
str += " ADD ("+columnInfo.getColumnName()+" "+ columnInfo.getDatatype() +"("+columnInfo.getColumnsize()+"));";
}
break;
case "DROP":
str += " DROP ("+columnInfo.getColumnName()+");";
break;
case "MODIFY":
if("NUMBER".equalsIgnoreCase(columnInfo.getDatatype()) || "DATE".equalsIgnoreCase(columnInfo.getDatatype())) {
str += " MODIFY ("+columnInfo.getColumnName()+" "+ columnInfo.getDatatype()+");";
} else {
str += " MODIFY ("+columnInfo.getColumnName()+" "+ columnInfo.getDatatype() +"("+columnInfo.getColumnsize()+"));";
}
break;
}
publishColumnInfoOutput(str);
}
public static Map<Integer, String> allJdbcTypeName = null;
public static Map<Integer, String> getAllJdbcTypeNames() {
Map<Integer, String> result = new HashMap<Integer, String>();
if(allJdbcTypeName != null)
return allJdbcTypeName;
try {
for (Field field : java.sql.Types.class.getFields()) {
result.put((Integer) field.get(null), field.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
return allJdbcTypeName=result;
}
public static String getStringPlaces(String[] attribs) {
String params = "";
for(int i=0; i<attribs.length; i++) { params += "?,"; }
return params.substring(0, params.length()-1);
}
}
列信息类
public class ColumnInfo {
private String schemaName;
private String tableName;
private String columnName;
private String datatype;
private String columnsize;
private String decimaldigits;
private String isNullable;
答案 12 :(得分:0)
为了完整性。
使用Java8
people.sort(Comparator.comparingInt(People::getId));
如果您想在descending order
people.sort(Comparator.comparingInt(People::getId).reversed());
答案 13 :(得分:0)
如果您使用的是 Java 8,那么最好使用以下代码:
Comparator<People> comparator = Comparator.comparing(People::getName);
然后简单地使用:
Collections.sort(list, comparator);
如果您使用的是 Java 7 或更低版本,那么您可以通过实现 compare 方法来使用比较器来自定义排序顺序。
例如:
import java.util.Comparator;
public class PeopleNameComparator implements Comparator<People> {
@Override
public int compare(People people1, People people2) {
return people1.getName().compareTo(people2.getName());
}
}
然后简单地像这样使用:
Collections.sort(list, new PeopleNameComparator);
答案 14 :(得分:-2)
不要浪费时间自己执行排序算法。代替;使用
Collections.sort()对数据进行排序。