[Java] ArrayList 이해하기
필그램
·2017. 8. 9. 03:14
일반 어레이와 달리 어레이리스트는 사이즈가 정해져 있지않다는 장점이 있다.
예를 들면
ArrayList<Aclass> al = new ArrayList<Aclass>(); 로 어레이리스트 객체를 만들수 있지만,
어레이는
Aclass[] arrayEx = new Aclass[100]; 처럼 갯수를 미리 지정해야한다.
어레이리스트(ArrayList) 생성방법
import java.util.ArrayList; public class Program { public static void main(String[] args) { // ArrayList 생성 ArrayList<Integer> el = new ArrayList<>(); // 배열 추가. el.add(1); el.add(5); el.add(10); // 출력할 갯수 int count = el.size(); //출력할 갯수 얻기 System.out.println("Count: " + count); // 출력내용 for (int i = 0; i < el.size(); i++) { int value = elements.get(i);
// 특정 위치를 출력 System.out.println("요소: " + value); } } }
출력결과
Count: 3 요소: 1 요소: 5 요소: 10
어레이리스트(ArrayList)에서 indexOf 과 lastIndexOf 는 인덱스의 위치를 출력하는 것이다.
el.add(10); 한뒤
int index = list.indexOf(1); int lastIndex = list.lastIndexOf(10);
int notFound = list.indexOf(200);
결과 출력
System.out.println(index); // 0 System.out.println(lastIndex); // 3 System.out.println(notFound); // -1
여기수 -1은 없다는 의미
SET사용해보기
el.set(0, "999");
결과값은
요소: 999 요소: 5 요소: 10
요소: 10
그밖의 알아둘것
Clear, isEmpty
// 비어있지 않으므로 프린트 안됨. System.out.println(el.isEmpty()); // 지우기 el.clear();
colors.remove(0);
최대값, 최소값 얻기
// Min and max.
int minimum = Collections.min(list);
int maximum = Collections.max(list);
System.out.println(minimum);
System.out.println(maximum);
}
정렬
Collections.sort(list);
for (String value : list) {
System.out.println(value);
}
'프로그래밍 > 모바일: iOS, Java, Android, Swift' 카테고리의 다른 글
[iOS 기초] 텍트스 입력 후, 키보드 없애기 (0) | 2017.08.14 |
---|---|
[iOS] Xcode 시뮬레이터에서 키보드 보는법 (0) | 2017.08.14 |
[Android,Java] 스트링(String) 입력문자를 인티저(Interger)로 바꾸기 (1) | 2017.08.03 |
[iOS] iOS 와 스위프트를 배우는 강좌입니다. (0) | 2017.07.31 |
안드로이드 레이아웃 인플레이션 ( LayoutInflater ) (0) | 2017.07.27 |