ArrayList<class>交换方法 [英] ArrayList&lt;class&gt; swap method

查看:21
本文介绍了ArrayList<class>交换方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public void sortDatabase(){
        for(int j=0;j<productDatabase.size()-1;j++){
        for(int i =0;i<productDatabase.size()-j-1;i++){
    if(compareTo(i)){
        Collections.swap(productDatabase,i,i++ );  //Με την Χρήση της Collections βιβλιοθήκης κάνω SWAP! Πρέπει να βάλω την βιβλιοθήκη όμως!

    }


    }
    }
}

public boolean compareTo(int index){

    if(productDatabase.get(index).getPrice() > productDatabase.get(index++).getPrice()){
        return true;
    }
    else
        return false;



}

上次我以非常糟糕的方式发布了我的答案.对不起,我的英语真的很烂,但这是我的问题.我已经声明了一个 ArrayList <产品类 > productDatabase .产品类中有一些字段.主要问题是我无法对 productDatabase 元素进行排序.

Last time i posted my answer in a very bad way. Sorry for my english that really suck , but here is my problem. I 've declared an ArrayList < class of Product > productDatabase . Product class has some fields in it. The main problem is that i cannot sort my productDatabase elements .

我使用 Collections.swap() 但即使我的 ArrayList 由另一个对象的元素组成,我也可以使用该方法吗?

I use Collections.swap() but can i use that method even if my ArrayList consists of elements that are another object ?

另外,我想让你看看我写的 compareTo 方法,它是布尔值并返回一个值以了解是否需要交换元素.

Also i want you to take a look at my compareTo method that i wrote which is boolean and returns me a value to know if swap of elements is needed.

提前致谢......并对我最近的第一篇糟糕的帖子感到抱歉.

Thanks in advance ... and feeling sorry for my latest first bad post.

推荐答案

无需通过使用 swap() 实现排序算法来重新发明轮子.Collections 已经提供了一个 sort() 方法,它使用了一个很好的归并排序实现.

There's no need to reinvent the wheel by implementing sorting algorithms using swap(). Collections already provides a sort() method using a nice implementation of mergesort.

实施Comparator 并使用 Collections.sort(List, Comparator)List进行排序自定义比较标准.

Implement a Comparator<Product> and use Collections.sort(List<T>, Comparator<T>) to sort the List according to a custom comparison criteria.

Comparator<Product> PRICE_COMPARATOR = new Comparator<Product>() { 
    @Override
    public int compare(Product o1, Product o2) {
        // Check for nulls if necessary
        return o1.getPrice().compareTo(o2.getPrice());
    }
}

List<Product> sortedList = Collections.sort(unsortedList, PRICE_COMPARATOR);

如果您的 List 不是 List,而是 List(它可能包含不属于Products),你可以实现一个 Comparator 并在其中使用 instanceof 来留下非 Product 项目在 List 的末尾.

If your List is not a List<Product>, but a List<Object> instead (it might contain items that are not Products), you could implement a Comparator<Object> and use instanceof inside it to leave non Product items at the end of the List.

或者迭代过滤它,同时只将Products添加到一个有序的数据结构中,例如TreeSet,提供你自己的Comparator.

Or iterate to filter it while adding only Products to an ordered data structure such as a TreeSet<Product>, providing your own Comparator<Product>.

这篇关于ArrayList<class>交换方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆