【问题标题】:Comparator in java not workingjava中的比较器不起作用
【发布时间】:2013-08-29 08:50:48
【问题描述】:

运行代码时出现以下错误 我是否应该在编写此方法的类中创建 Mycomp 类的对象

Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments 

(列表)。推断类型 Product 不是有界参数的有效替代 >

    public List<Product> displaySortedShoppingCart(String userName) throws ShoppingCartNotFoundException
{
    getConnection();
    ResultSet rs;
    boolean flag=false;
    List<Product> l=new ArrayList<Product>();
    String sql="select *from scart where username='"+userName+"'";
    try {
        rs=stmt.executeQuery(sql);
        while(rs.next())
        {
            flag=true;
            Product pr=new Product();
            pr.setname(rs.getString(2));
            l.add(pr);
            //System.out.println(rs.getString(2));
        }
        if(flag==false)
            throw new ShoppingCartNotFoundException();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //SortProduct sp=new SortProduct(new Product());

    Collections.sort(l);
    return l;
}

我的 Comparator 实现类如下

import java.util.Comparator;

import com.bean.Product;


public class SortProduct implements Comparator {

    @Override
    public int compare(Object o1,Object o2)
    {

    Product p1=(Product)o1;

    Product p2=(Product)o2;

    int temp=p1.getName().compareTo(p2.getName());
    return temp;
    }

}

【问题讨论】:

  • 您应该使用 Collections.sort(l) 其中 l 是您正在编写的列表的对象 Collections.sort((pr) 这是错误的第一个错误是您没有右括号,其他是不是方法排序的有效参数,它应该是任何实现集合的对象

标签: java collections comparator


【解决方案1】:

第 1 步:将您的比较器输入为Comparator&lt;Product&gt;

public class SortProduct implements Comparator<Product> {
    @Override
    public int compare(Product p1, Product p2) {
        return p1.getName().compareTo(p2.getName());
    }
}

请注意代码的输入方式更简洁 - 无需强制转换。

第 2 步:将 Comparator 的一个实例传递给 sort 方法:

Collections.sort(l, new SortProduct());

【讨论】:

    【解决方案2】:

    当你使用Collections.sort(l);时,你的产品类必须实现Comparable

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 2015-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多