具有一个对象,该对象表示带有日期,名称,文本和类型的数据条目,并使其实现Comparable接口. Comparable接口有效地允许对对象执行不等式运算,这是Java API用于对对象进行任何形式的比较(用于排序)的方法.然后,要根据给定的字段对数据进行排序,请在数据对象类中包含一个静态变量,该变量表示要对哪个字段进行排序.
class Data implements Comparable
{
int date; // field 1
String name; // field 2
String text; // field 3
int type; // field 4
static int sortField;
static final int DATE = 1;
static final int NAME = 2;
static final int TEXT = 3;
static final int TYPE = 4;
// put constructor here
//compareTo function for sorting
public int compareTo(Data other)
{
if (sortField == DATE)
{
if (date < other.date) return -1;
if (date > other.date) return 1;
else return 0;
}
if (sortField == NAME)
{
return name.compareTo(other.name);
}
if (sortField == TEXT)
{
return text.compareTo(other.text);
}
else
{
if (type < other.type) return -1;
if (type > other.type) return 1;
else return 0;
}
}
}
然后,您要做的就是将对象放入ArrayList并对其进行排序
ArrayList list = new ArrayList();
//put Data objects into list here
//to sort
Data.sortField = Data.DATE; //sort by date - change as needed
Collections.sort(list);