Java Collections Framework 의 일원이며 Collection 객체들을(set, list, map ..... ) 유용하게 사용하기위한 util class이다.

주로 연산작업이나 콜렉션객체를 리턴한다.

 

Field

  • EMPTY_LIST
  • EMPTY_MAP
  • EMPTY_SET

        모두 직렬화가 가능하며 사이즈가 0인 객체를 만들어 준다. 각각 emptyList(), emptyMap(), emptySet() 메소드와 동일한 기능을 수행 함. (null값이 들어간 객체가 아닌 말그대로의 빈객체이므로 NullPointException이 발생하지 않는다)

 

Method

  • sort  :  public static <T extens Comparable<? super T>> void sort(List<T> list)
                  public static <T> void sort(List<T> list, Comporator<? super T> c)
    리스트 객체를 정렬해주는 메소드 comparble을 implements한 클래스를 이용해 정렬 할 수도 있고, Comparator를 이용해 조건을 여러개 주어서 검색할 수도 있다.
    Comparable 이나 Comparator 응용 방법 링크
  • 01 import java.util.ArrayList;
    02 import java.util.Collections;
    03 import java.util.Comparator;
    04 
    05 import java.lang.Comparable;
    06 
    07 public class TestCollections {
    08     public static void main(String args[]) throws Exception {

    09         ArrayList<PersonalInfo> list = new ArrayList();
    10         list.add(new PersonalInfo("홍길동","11-11-11"));
    11         list.add(new PersonalInfo("김개똥","66-66-66"));
    12         list.add(new PersonalInfo("정지훈","66-66-66"));
    13         list.add(new PersonalInfo("정지훈","44-44-44"));
    14         list.add(new PersonalInfo("이소라","33-33-33"));
    15         list.add(new PersonalInfo("손예진","55-55-55"));
    16         System.out.println("====== 정렬전 ======");
    17         for(int idx = ; idx < list.size() ; idx++) {
    18           System.out.println(list.get(idx).getName() ", " 
    19                            + list.get(idx).getPhoneNumber());
    20         }
    21         Collections.sort(list);
    22         System.out.println("====== 정렬후 ======");
    23         for(int idx = ; idx < list.size() ; idx++) {
    24           System.out.println(list.get(idx).getName() ", " 
    25                            + list.get(idx).getPhoneNumber());
    26         }
    27         //@Override  여러검색조건을 선택할때 사용
    28         Comparator<PersonalInfo> comparator = 

    29           new Comparator<PersonalInfo>(){

    30           public int compare(PersonalInfo o1, PersonalInfo o2) {

    31            return o1.getName().compareToo2.getPhoneNumber() );
    32           }      
    33          };
    34         Collections.sortlist, comparator );
    35         System.out.println("====== 정렬후 ======");
    36         for(int idx = ; idx < list.size() ; idx++) {
    37           System.out.println(list.get(idx).getName() ", " 
    38                            + list.get(idx).getPhoneNumber());
    39         }
    40     }
    41 }
    42 //검색조건이 하나일 때 유용.

    43 class PersonalInfo implements Comparable<PersonalInfo>{
    44  
    45   private String name = null;
    46   private String phoneNumber = null;
    47   private boolean sortingMode = false;
    48   
    49   public PersonalInfo(String name, String phoneNumber) {
    50     this.name = name;
    51     this.phoneNumber = phoneNumber;
    52     this.sortingMode = true;
    53   }
    54  
    55   public void setName(String name) {   
    56     this.name = name; 
    57   }
    58   public void setPhoneNumber(String phoneNumber) {  
    59     this.phoneNumber = phoneNumber; 
    60   }
    61   public void setSortingMode(boolean sortingMode) {  
    62     this.sortingMode = sortingMode; 
    63   }
    64  
    65   public String  getName() {  return name; }
    66   public String  getPhoneNumber() {  return phoneNumber; }
    67   public boolean getSortingMode() {  return sortingMode; }
    68  
    69   //@Override
    70   public int compareTo(PersonalInfo o) {
    71     return name.compareToo.getName() );
    72   }
    73 
    74 }

     

    결과 값 :

    ====== 정렬전 ======
    홍길동, 11-11-11
    김개똥, 66-66-66
    정지훈, 66-66-66
    정지훈, 44-44-44
    이소라, 33-33-33
    손예진, 55-55-55
    ====== 정렬후 ======
    김개똥, 66-66-66
    손예진, 55-55-55
    이소라, 33-33-33
    정지훈, 66-66-66
    정지훈, 44-44-44
    홍길동, 11-11-11
    ====== 정렬후 ======
    홍길동, 11-11-11
    정지훈, 44-44-44
    정지훈, 66-66-66
    이소라, 33-33-33
    손예진, 55-55-55
    김개똥, 66-66-66


  • binarySearch :
    public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key)
    public static <T> int binarySearch(List<? extends T> list, T key,  Comparator<? super T> c)
    메소드 수행전 반드시 정렬되어있어야 하며, 정렬되지 않았을 때 수행시 결과값은 undefined 된다. 검색 결과가 여러개일 경우 랜덤하게 추출하기 때문에 원하는 값을 보장하지 않는다. 결과값이 없을 경우 : (-(insertion point) - 1).
  • reverse : pubic static void reverse(List<?> list)
    리스트를 역순으로 정렬시킨다. (순차정렬이 아님)
  • suffle : public static void shuffle(List<?> list)
                    public static void shuffle(List<?> list,  Random rnd)
    랜덤하게 리스트를 섞는다.
  • swqp : public static void swap(List<?> list, int i, int j)
    i와 j 포지션의 위치를 서로 바꾼다. IndexOutOfException에 주의할 것
  • fill : public static <T> void fill(List<? super T> list, T obj)
    obj 값으로 모든 엘리먼트들을 변경한다
  • copy : public static <T> void copy(List<? super T> dest, List<? extends T> src )
    src리스트의 모든 엘리먼트들을 dest 리스트에 카피한다. 반드시 dest 리스트가 src리스트보다 커야하며, 아닐 경우 IndexOutOfException이 발생한다.
  • min :
    public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll )
    public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll, Comparator <? Super T>comp )
    최소값을 구한다. 자동소팅된다. 결과값이 여러개일 경우 Comparator 를이용해 처리한다.
  • max :
    public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll )
    public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll, Comparator <? Super T>comp )
    최대값을 구한다. 자동소팅된다. 결과값이 여러개일 경우 Comparator 를이용해 처리한다.
  • rotate : public static void rotate(List<?> list,  int distance)
    distance만큼 옆으로 이동한다. 양수일경우 오른쪽, 음수일경우 왼쪽으로 이동 된다. list.size()보다 클 순 없다.
    보통 subList를 이용해 많이 활용된다. Collections.rotate( list.subList(j, k+1), distance)
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 의 엘리먼트를 갖는 리스트의 경우
    Collections.rotate( list.subList(2,5), 1) ); 수행 하면
    [1, 2, 5, 3, 4, 6, 7, 8, 9, 10] 로변경된다.
  • replaceAll : public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal)
    list에서 oldVal값을 찾아서 newVal값으로 변경 (oldVal == null ? e == null : oldVal.equals(e))
  • indexOfSubList : public static int indexOfSubList(List<?> source, List<?> target)
    source리스트에서 target리스트를 검색. source리스트에서 검색되면 가장 첫번째인덱스(lowest index )를 리턴한다. 검색이 되지 않을 경우 -1을 리턴한다.
  • lastIndexOfSubList : public static int lastIndexOfSubList(List<?> source, List<?> target)
    source리스트에서 target리스트를 검색. source리스트에서 검색되면 가장 첫번째인덱스(highest index )를 리턴한다. 검색이 되지 않을 경우 -1을 리턴한다.
  • unmodifiableCollection : public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)
    읽기전용의 뷰컬렉션을 리턴한다. 컬렉션의 내용을 변경하게 되면 java.lang.UnsupportedOperationException 이 발생함. 각특성은  document확인
    동일기능의 메소드 -
    unmodifiableSet : public static <T> Set<T> unmodifiableSet(Set<? extends T> s )
    unmodifiableSortedSet : public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s )
    unmodifiableList : public static <T> List<T> unmodifiableList(List<? extends T> list )
    unmodifiableMap : public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K,? extends V> m)
    unmodifiableSortedMap : public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K,? extends V> m )
  • synchronizedCollection : public static <T> Collection<T> synchronizedCollection(Collection<T> c )
    컬렉션 동기화 . 동기화된 컬렉션을 리턴받아 Iterator를 사용하여, 리턴된 컬렉션을 반복처리하는 경우에는, 특별히, synchronized 블럭과 함께 사용해야 한다. 각 특성은 document 확인
    동일기능의 메소드 -
    synchronizedSet : public static <T> Set<T> synchronizedSet(Set<T> s )
    synchronizedSortedSet : public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s )
    synchronizedList : public static <T> List<T> synchronizedList(List<T> list )
    synchronizedMap : public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m )
    synchronizedSortedMap : public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m )




  •  

     





[출처 : http://blog.naver.com/ily1201/91140240]

+ Recent posts