List排序的问题

1.对List进行排序可以通过这种方式,实现(implements) Comparable<T>接口
@Override
    public int compareTo( T  o)
    {
        if (null == o)
        {
            return -1;
        }

        RunningInstancesItemType instance0 = this.instanceInfo;
        RunningInstancesItemType instance1 = o.getInstanceInfo();

        if (null == instance0 || null == instance1)
        {
            return -1;
        }
        else
        {
            // 按运行时间排序
            String launchTime0 = this.getInstanceInfo().getLaunchTime();
            String launchTime1 = o.getInstanceInfo().getLaunchTime();
            if (!launchTime0.equals(launchTime1))
            {
                return launchTime1.compareTo(launchTime0);
            }
            else
            {
                // 如果运行时间相同,则按Id排序
                String instanceId0 = this.getInstanceInfo().getInstanceId();
                String instanceId1 = o.getInstanceInfo().getInstanceId();
                return instanceId0.compareTo(instanceId1);
            }
        }
    }

    @Override
    public boolean equals(Object obj)
    {
        boolean equals;

        if (null == obj)
        {
            equals = false;
        }
        else if (this == obj)
        {
            equals = true;
        }
        else if (this.getClass() != obj.getClass())
        {
            equals = false;
        }
        else
        {
            InstanceBean o = (InstanceBean)obj;
            RunningInstancesItemType instance1 = this.instanceInfo;
            RunningInstancesItemType instance2 = o.getInstanceInfo();

            if (null == instance1 || null == instance2)
            {
                equals = false;
            }
            else
            {
                if (null == instance1.getLaunchTime())
                {
                    equals = false;
                }
                else
                {
                    equals = instance1.getLaunchTime().equals(instance2.getLaunchTime());
                }
            }
        }

        return equals;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((null == this.getInstanceInfo() || null == this.getInstanceInfo().getLaunchTime()) ?
                        0 : this.getInstanceInfo().getLaunchTime().hashCode());
        return result;
    }

2.也可以使用TreesSet实现
SortedSet<T> sortedSet = new TreeSet<T>();
List<T> instanceList;
sortedSet.add(***);//此处*为T的实例化
instanceList = new ArrayList<T>(sortedSet);

你可能感兴趣的:(list,Java排序)