TreeSetの使用:一連の数の異なる数を取得(ソート)

1372 ワード

import java.io.BufferedInputStream;

import java.util.Iterator;

import java.util.Scanner;

import java.util.Set;

import java.util.TreeSet;



public class Main {

	public static void main(String[] args) {

		Scanner cin = new Scanner(new BufferedInputStream(System.in));

		Set<Number> numberSet = new TreeSet<Number>();

		int[] numberArrays = null;

		int nalength = -1;

		Number num = null;

		while (cin.hasNext()) {

			System.out.print(" :");

			nalength = cin.nextInt();

			System.out.print("
:"); numberArrays = new int[nalength]; for (int i = 0; i < nalength; i++) { numberArrays[i] = cin.nextInt(); num = new Number(numberArrays[i]); numberSet.add(num); } Iterator<Number> iter = numberSet.iterator(); System.out.print("
, :
"); while (iter.hasNext()) { System.out.print(iter.next().number); if (iter.hasNext()) { System.out.print(" "); } } System.out.println(); } } } class Number implements Comparable<Number> { int number; Number(int number) { this.number = number; } @Override public int compareTo(Number num) { int res = this.number - num.number; if (res > 0) { return 1; } else if (res < 0) { return -1; } return 0; } }