자바

Collections 클래스(sort, reverse, min, max, binaryResearch)

긴가우딘 2024. 6. 8. 17:02
  • sort(): 정렬
  • reverse(): 반대로 정렬
  • max(), min(): 최대, 최소 구하기
  • binarySearch(): 이진 검색

 

Collections 클래스의 메소드는 모두 static 타입이므로 Collections 객체를 생성할 필요가 없다

 

Math.max()와 Collections.max()의 차이점이 뭘까?

  • Math.max()는 두 숫자 중 큰 수를 반환
  • Collections.max()는 컬렉션 내에서 가장 큰 수를 반환 - 즉 List나 Set에서 사용

 

public Static void main(String[] args) {
	LinkedList<String> myList = new LinkedList<String()>;
	myList.add("a");
	myList.add("b");
	myList.add("c");
	myList.add(0, "d");
	myList.add(2, "e");
	
	Collections.sort(myList); // a b c d e
	Collections.reverse(myList); // e d c b a

	int index = Collections.binarySearch(myList, "c") + 1;
	System.out.println("c는  " + index + "번째 요소입니다."); // 3번째