-2

我有一个数组列表,现在我想对其进行排序,我的数组列表也包含重复元素,重复元素也应在最终结果排序列表中删除,请告知

 ArrayList list=new ArrayList();
      list.add("Ram");
       list.add("Dinesh");
      list.add("Sachin");
      list.add("Dinesh");
4

2 回答 2

1

没有一些迭代是不可能进行排序的,但你不必自己做。尝试使用对插入进行排序并删除重复项的排序集:

list = new ArrayList<String>( new TreeSet<String>(list) );

基本上,您将列表内容放入已排序的集合(TreeSet在本例中为 a),然后将该集合的内容复制回新列表中。

于 2012-04-28T05:13:21.623 回答
0

同上。如果要对创建的对象的集合进行排序,则需要让 Collections 和 Arrays 知道如何比较对象。

import java.util.Arrays;

public class delme {
    public static void main(String[] args)
    {

        SomeData[] theData = new SomeData[5];
        theData[0] = new SomeData("zzzz", 1);
        theData[1] = new SomeData("aaaa", 1);
        theData[2] = new SomeData("zzzz", 0);
        theData[3] = new SomeData("aaaa", 0);
        theData[4] = new SomeData("aaaa", 0);

        Arrays.sort(theData);

        for (int i = 0; i < theData.length; i++){
            System.out.println("theData[" + i + "]=" + theData[i].toString());
        }
    }
  }


  public class SomeData implements Comparable {

    public String someData1;
    public int someData2;


    public SomeData(String s, int i) {
        someData1 = s;
        someData2 = i;
    }


    //return -1 if this object should come before the arguments object in a sorted list
    //return 0 if they have the same value
    //return 1 if this object should come after in a sorted list
    public int compareTo(Object arg0) throws ClassCastException {
        if (!(arg0 instanceof SomeData)) //we must accept type Object so lets check to make sure its of type SomeData
            throw new ClassCastException("peram given is not a SomeData object");

        SomeData otherData = (SomeData)arg0; //lets cast it to our data type for ez access
        if (someData2 == otherData.someData2)
            return someData1.compareTo(otherData.someData1);
        return Integer.compare(someData2, otherData.someData2);
    }

    public String toString() {
        return "someData1=" + someData1 + ", someData2=" + someData2;
    }
  }
于 2012-04-28T05:42:37.963 回答