18
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ArrayList<自作クラス>のソートで昇順、降順をよく忘れるのでメモ

Last updated at Posted at 2014-09-09

compareメソッドのOverrideで「どっちか昇順だっけ?」って、よくやってしまう

昇順(1,2,3,4,...)にソート

修正:同じ値の時は0を返すべきとの指摘を受けました。ありがとうございます。ifでやるのではなく、Double.compare(Double v1, Double v2)を使用するようにする

注意点

Overrideするcompareメソッドでは、int型を返す。Double型を基準にソートする場合、return v1 - v2;ができないreturn (int)(v1-v2);も小数点以下が切り捨てされるので、正確にソートされない

Hoge.java
package hoge;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Main {
	public static void main(String... args) {
		ArrayList<Hoge> hogeList = new ArrayList<>();
		hogeList.add(new Hoge());
		hogeList.add(new Hoge());
		hogeList.add(new Hoge());
		System.out.println("Before");
		for (Hoge hoge : hogeList) {
			System.out.print(hoge + ",");
		}

		Collections.sort(hogeList, new HogeComp());

		System.out.println("\nAfter");
		for (Hoge hoge : hogeList) {
			System.out.print(hoge + ",");
		}
	}

	private static final class Hoge {
		private final Double value;
		private Hoge() {
			this.value = (int)(Math.random() * 1000) / 100.0;
		}

		@Override
		public String toString() {
			return this.value.toString();
		}
	}

	private static final class HogeComp implements Comparator<Hoge> {
		@Override
		public int compare(Hoge o1, Hoge o2) {
			return Double.compare(o1.value, o2.value);
		}
		
	}
}

結果

Before
2.84,3.08,1.07,
After
1.07,2.84,3.08,

降順(5,4,3,2,...)

  • 昇順でソートして、Collections.reverse(list)
18
16
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?