我正在学习Java和排序。
我有一个关于跟踪重复值的索引号的问题。
例如,我们有表格,我将所有数据都放入ArrayList
,如下所示:
ArrayList = {FOO , AA, BOB, AA, BOB}
Index | Value
1 | FOO
2 | AA
3 | BOB
4 | AA
5 | BOB
现在我想对数据进行排序:
Index | Value
2 | AA
4 | AA
3 | BOB
5 | BOB
1 | FOO
有没有办法保留唯一索引和排序数据?
感谢。
答案 0 :(得分:1)
创建一个类
class DataHelper{
private String name;
private int index;
// other stuff
}
并创建List<DataHelper>
并撰写Comparator
以对DataHelpers
答案 1 :(得分:0)
您可以使用以下内容对Arraylist或任何Collection子类进行排序。
// unsortstList is an ArrayList
Collections.sort(unsoredtList);
答案 2 :(得分:0)
创建一个既包含索引又包含文本字符串的对象。像
public class MyThing
{
public int index;
public String text;
}
然后,不是创建字符串的ArrayList,而是创建这些对象的ArrayList。
我不知道你用什么来分类它们。如果你正在编写自己的排序,那么你可以简单地对每个对象的“text”成员进行比较,而不是对着字符串对象本身进行比较。如果您正在使用Arrays.sort对其进行排序,那么您需要实现Comparable。即:
public class MyThing implements Comparable<MyThing>
{
public int index;
public String text;
public int compareTo(MyThing that)
{
return this.text.compareTo(that.text);
// May need to be more complex if you need to handle nulls, etc
}
// If you implement compareTo you should override equals ...
public boolean equals(Object that)
{
if (!(that instanceof MyThing))
{
return false;
}
else
{
MyThing thatThing=(MyThing)that;
return this.text.equals(thatThing.text);
}
}
}
等。根据您的目的,您可能需要其他东西。
答案 3 :(得分:0)
你可以有这种格式
import java.util.ArrayList;
import java.util.Collections;
public class MyData implements Comparable<MyData>{
private Integer index;
private String value;
public MyData(Integer index, String value) {
this.index = index;
this.value = value;
}
/**
* @return the index
*/
public Integer getIndex() {
return index;
}
/**
* @param index the index to set
*/
public void setIndex(Integer index) {
this.index = index;
}
/**
* @return the value
*/
public String getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(String value) {
this.value = value;
}
public int compareTo(MyData o) {
int compare = this.value.compareTo(o.getValue());
if(compare ==0){
compare = this.index.compareTo(o.getIndex());
}
return compare;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "MyData [index=" + index + ", value=" + value + "]";
}
public static void main(String arg[]){
List<MyData> mySet = new ArrayList<MyData>();
mySet.add(new MyData(1,"FOO"));
mySet.add(new MyData(2,"AA"));
mySet.add(new MyData(3,"BOB"));
mySet.add(new MyData(4,"AA"));
mySet.add(new MyData(5,"BOB"));
Collections.sort(mySet);
System.out.println(mySet);
}
}