ArrayList的&LT;类别和GT;交换方法 [英] ArrayList<class> swap method
问题描述
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&LT;类产品> 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.
推荐答案
有没有必要使用交换实现排序算法推倒重来()
。 收藏
已经提供了使用一个很好的实现归并的排序()
方法。
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.
实现一个 比较&LT;产品&GT;
,并使用<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29\"相对=nofollow> Collections.sort(名单&LT; T&GT ;,比较&LT; T&GT;)
到列表<排序/ code>根据自定义比较标准。
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);
如果你的列表
不是列表&LT;产品&GT;
,但列表&LT;对象&gt;
代替(它可能包含不产品
的项目进行),你可以实现一个比较&LT;对象&gt;
,并使用的instanceof
里面它在<$ C结束后离开非产品
项目$ C>列表。
If your List
is not a List<Product>
, but a List<Object>
instead (it might contain items that are not Product
s), you could implement a Comparator<Object>
and use instanceof
inside it to leave non Product
items at the end of the List
.
或者iterate对其进行过滤,而只增加产品
来一个有序的数据结构,如 TreeSet的&LT;产品&GT;
,提供自己的比较&LT;产品方式&gt;
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的&LT;类别和GT;交换方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!