자바 Generic 알아보기
Java 2015. 4. 6. 23:46자바의 generic type은 형의 안정성을 보장한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | package com.java.collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; class Mountain{ String name; int height; Mountain(String n, int h){ this.name=n; this.height=h; } public String getName(){ return this.name; } public int getHeight(){ return this.height; } public String toString(){ return this.name + " " + this.height; } } public class SortMountains { LinkedList<Mountain> mtn = new LinkedList<Mountain>(); class NameCompare implements Comparator<Mountain>{ @Override public int compare(Mountain one, Mountain two){ return one.getName().compareTo(two.getName()); } } class HeightCompare implements Comparator<Mountain>{ @Override public int compare(Mountain one, Mountain two){ // 양수 내림차순, 음수 올림차순 return one.getHeight() - two.getHeight(); } } public static void main(String [] args){ new SortMountains().go(); } public void go(){ mtn.add(new Mountain("Longs", 14255)); mtn.add(new Mountain("Elbert", 14433)); mtn.add(new Mountain("Maroon", 14156)); mtn.add(new Mountain("Castle", 14265)); System.out.println("as entered:\n" + mtn); NameCompare nc = new NameCompare(); Collections.sort(mtn, nc); System.out.println("by name;\n" + mtn); HeightCompare hc = new HeightCompare(); Collections.sort(mtn, hc); System.out.println("by height;\n" + mtn); } } | cs |