Android Java List 排序

原文章转自网上blog,但是其中代码运行后原来的list排序根本没有改变。

于是打开Comparator文档看了,发现原代码的compare函数实现的返回值有问题!

修正后运行结果正确了,代码如下:

	@SuppressWarnings("unchecked")
	void test() {
		ArrayList list = new ArrayList();
		list.add(new Person("lcl 28", 28));
		list.add(new Person("fx 23", 23));
		list.add(new Person("wqx 29", 29));
		list.add(new Person("qd 20", 20));
		list.add(new Person("xgw 69", 69));
		Comparator comp = new Comparator() {
			public int compare(Object o1, Object o2) {
				Person p1 = (Person) o1;
				Person p2 = (Person) o2;
				if (p1.age < p2.age)
					return -1;
				else if (p1.age == p2.age)
					return 0;
				else if (p1.age > p2.age)
					return 1;
				return 0;
			}
		};
		Collections.sort(list, comp);

		for (int i = 0; i < list.size(); i++) {
			Person p = (Person) list.get(i);
			System.out.println(p.getName());
		}
	}

	public static class Person {

		private int age;
		private String name;

		public Person(String name, int age) {
			this.age = age;
			this.name = name;
		}

		public int getAge() {
			return age;
		}

		public void setAge(int age) {
			this.age = age;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
	}


你可能感兴趣的:(java,android,String,list,object,Class)