Java 对item类中的元素进行排序
我有一个Java 对item类中的元素进行排序,java,Java,我有一个Item类,它有id,count,name作为实例变量。我想根据数量对物品进行排序。请告诉我怎么做。我可以在item类中定义任何方法来对项目进行排序吗 下面是我的项目类 公共类项目{ 私有字符串id; 私有字符串计数; 私有字符串名称; 项目({ } 公共字符串getcount(){ 返回这个.count; } 公共项(字符串名称){ this.name=名称; this.id=“”; } 公共项(字符串id、字符串名称){ this.name=名称; this.id=id; } 公共项
Item
类,它有id
,count
,name
作为实例变量。我想根据数量对物品进行排序。请告诉我怎么做。我可以在item类中定义任何方法来对项目进行排序吗
下面是我的项目类
公共类项目{
私有字符串id;
私有字符串计数;
私有字符串名称;
项目({
}
公共字符串getcount(){
返回这个.count;
}
公共项(字符串名称){
this.name=名称;
this.id=“”;
}
公共项(字符串id、字符串名称){
this.name=名称;
this.id=id;
}
公共项(字符串id、字符串名称、字符串计数){
this.name=名称;
this.id=id;
这个.count=count;
}
公共字符串getItemName(){
返回此.name;
}
公共字符串getItemId(){
返回此.id;
}
public void createItem(字符串id、字符串名称){
this.name=名称;
this.id=id;
}
公用项目返回项目(项目列表项目集){
Item=null;
退货项目;
}
}
我还有一个ItemList
类,它保存项目
public类ItemList实现了Iterable{
private List hold=new ArrayList();
项目列表(项目){
//hold=新的ArrayList();
此.保持.添加(项);
}
项目列表(){
//抛出新的UnsupportedOperationException(“尚未实现”);
}
公共列表getItemList(){
把这个还给我;
}
公共无效附加项(项){
//hold=新的ArrayList();
此.保持.添加(项);
}
@凌驾
公共迭代器迭代器(){
迭代器项=hold.Iterator();
退货项目;
}
}
编写自定义比较器并使用
Collections.sort(collections, yourComparator);
您需要实现可比较的接口
请参见您的类应该实现和方法。这里有一个。实现可比较的接口,并编写排序顺序逻辑
public class Item implements Comparable<Item>{
private String id;
private String count;
private String name;
Item() {}
...
public int compareTo(Item item1) {
return this.count.compareTo(item1.count);
}
}
公共类项实现可比较{
私有字符串id;
私有字符串计数;
私有字符串名称;
项(){}
...
公共整数比较(项目1){
返回此.count.compareTo(item1.count);
}
}
现在,您可以按集合#排序
或数组#排序
对对象进行排序
特别是,您应决定是否需要:
注意,如果您愿意,您可以同时执行这两项操作。-如果您希望仅以一种方式对其排序,请使用
java.lang.Compariable
接口
-使用
java.util.Comparator
接口,如果您想以多种方式对其进行排序请使用比较器
:
List<Item> lstItem = new ArrayList<Item>();
//fill the data...
Comparator<Item> comparator = new Comparator<Item>() {
public int compareTo(Item i1, Item i2) {
return i1.count.compareTo(i2.count);
}
};
Collections.sort(lstItem, comparator);
List lstItem=new ArrayList();
//填写数据。。。
比较器比较器=新比较器(){
公共整数比较(项目i1、项目i2){
返回i1.count.compareTo(i2.count);
}
};
Collections.sort(lstItem,comparator);
在这里询问之前,你能在谷歌上搜索吗。有很多信息…奇怪,但是count
属性是String
,而不是数字。谢谢通知。我真的错过了。