ArrayList<class> swap method

隐身守侯 提交于 2019-12-11 08:13:22

问题


  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;



}

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 .

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

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.


回答1:


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.

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);

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.

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



来源:https://stackoverflow.com/questions/19765243/arraylistclass-swap-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!