프로그래밍 공부/JAVA
JAVA- Collection (LIST)
뚜뚜:)
2020. 11. 3. 08:41
- ArrayList 는 기본적인 사용법이 Vector와 같다.
데이터 추가 : add( );
ArrayList list1 = new ArrayList();
list1.add("sss");
list1.add("bbb");
list1.add(123);
list1.add('s');
list1.add(false);
list1.add(123.45);
System.out.println("list1의 siz는 " + list1.size());
System.out.println("list : " + list1);
데이터 꺼내오기 : get( );
System.out.println("1번째 자료 : " + list1.get(1));
데이터 끼워넣기 : set( );
String temp = (String)list1.set(3,"XXX");
System.out.println("temp : " + temp);
System.out.println("list1" + list1);
데이터 삭제하기 : remove( );
list1.remove(3);
list1.remove("삭제 후 list1 :" + list1);
list1.remove("bbb");
System.out.println("삭제후 list : " + list1);데이터 삭제하기 : remove( );
비교객체 : contais(비교객체)
- 리스트에 '비교객체'가 있으면 true, 없으면 false 반환
System.out.println("DDD값 : " + list2.contains("DDD")); //true
System.out.println("zzz값 : " + list2.contains("zzz")); //false
비교객체 2 : indexOf(비교객체)
- 리스트에 비교객체가 있으면 비교객체가 있는 위치의 index값이 반환된다.
==> 반환값이 있으면 인덱스의 값, 없으면 -1을 반환
System.out.println("DDD의 위치값 : " + list2.indexOf("DDD")); //3
System.out.println("ZZZ의 위치값 : " + list2.indexOf("zzz")); //-1
배열 : toArray()
- 리스트안의 데이터를 배열로 변환하여 반환한다 (기본적으로 object형 배열로 변환한다)
Object[] strArr = list2.toArray();
System.out.println("list2의 배열의 개수 : " + strArr.length);
//배열안의 값을 꺼내올 때 for문 사용
for (int i = 0; i < strArr.length; i++) {
System.out.println(i + " 번째 자료 : " + strArr[i]);
}
//String 타입으로 바꾸기 -> 그냥 쓰면 에러 발생
//toArray(new 제네릭타입[0]) -> []안의 숫자는 아무거나 사용가능, [1000]이어도 됨/
//==> 제네릭 타입의 배열로 변환한다.
System.out.println("=============string 타입 사용 ============");
String[] strArr1 = list2.toArray(new String[0]);
System.out.println("list2의 배열의 개수 : " + strArr1.length);
//배열안의 값을 꺼내올 때 for문 사용
for (String str : strArr1) {
System.out.println("배열의 값 :" + str);
}
* 변수를 선언해주면, 1차원 배열의 객체를 생성하여 주소를 넣어준다.
String[] ttt = new String[0];
String[] StrArr2 = list2.toArray(ttt);
System.out.println(StrArr2.length);