Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 对item类中的元素进行排序_Java - Fatal编程技术网

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
    ,而不是数字。谢谢通知。我真的错过了。