[英]How to sort an arraylist of objects java?
所以我想在java中使用對象的arraylist。
我有object1.number
和object2.number
, object3.number
,等等......但這些對象除了具有其他屬性number
,如name
, distance
,等...
因此,如果它正在對array
的字符串進行排序,那么就是將字符串放在一個temporal
,讓另一個字符串取代它......但是在對象的araryList
中,我該怎么做呢?
我可以將對象移動到數組的那個位置嗎?
謝謝。
實現自己的比較器:
Arrays.sort(yourArray, new Comparator<YourClass>() {
@Override
public int compare(YourClass o1, YourClass o2) {
//compare object properties
}
});
您需要實現類似的界面
implements Comparable
做這項工作的方法是
public int compareTo(Object obj)
{
}
請注意,對象通常由full on類型替換,因為通用語法可以在implements語句中使用(如下所示)。
一個完整的例子就在教程文檔中,希望這會有所幫助
一個完整的例子(從上面的鏈接中取出如下),我已經添加了這個,以防鏈接在某些時候失效
import java.util.*;
public class Name implements Comparable<Name> {
private final String firstName, lastName;
public Name(String firstName, String lastName) {
if (firstName == null || lastName == null)
throw new NullPointerException();
this.firstName = firstName;
this.lastName = lastName;
}
public String firstName() { return firstName; }
public String lastName() { return lastName; }
public boolean equals(Object o) {
if (o == null || !(o instanceof Name))
return false;
Name n = (Name) o;
return n.firstName.equals(firstName) && n.lastName.equals(lastName);
}
public int hashCode() {
return 31*firstName.hashCode() + lastName.hashCode();
}
public String toString() {
return firstName + " " + lastName;
}
public int compareTo(Name n) {
int lastCmp = lastName.compareTo(n.lastName);
return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));
}
}
該文章中的客戶端代碼是:
import java.util.*;
public class NameSort {
public static void main(String[] args) {
Name nameArray[] = {
new Name("John", "Smith"),
new Name("Karl", "Ng"),
new Name("Jeff", "Smith"),
new Name("Tom", "Rich")
};
List<Name> names = Arrays.asList(nameArray);
Collections.sort(names);
System.out.println(names);
}
}
您需要使用比較器來實現此目的。
根據您的問題,我認為您應該自己實施排序算法。 如果是這種情況,您可以操縱ArrayList中元素的位置,它只是與常規數組有點不同。 看看add(int index, E element)
。 index
參數允許您決定在ArrayList中添加元素的位置。
要像傳統數組那樣操作ArrayList的條目,請使用ArrayList.set(int,E)。
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#set%28int,%20E%29
使用Collections.sort()
在Java 8中對ArrayList進行排序:
Collections.sort(array, new Comparator<Class>() {
@Override
public int compare(Class o1, Class o2) {
//compare object properties
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.