List기본 연습
기본연습
리스트에 요소를 추가하기
public class ExerciseList {
public static void main(String[] args) {
List<String> listExercise = new ArrayList<String>();
listExercise.add("ABC");
listExercise.add("D");
listExercise.add("XYZ");
System.out.println(listExercise);
}
}
[ABC, D, XYZ]
리스트에 요소를 덮어 쓰기
import java.util.ArrayList;
import java.util.List;
public class ExerciseList {
public static void main(String[] args) {
List<String> listExercise = new ArrayList<String>();
listExercise.add("ABC");
listExercise.add("D");
listExercise.add("XYZ");
System.out.println("before : " + listExercise);
// Overwrite index 0
listExercise.set(0, "xxx");
System.out.println("after : " + listExercise);
}
}
before : [ABC, D, XYZ]
after : [xxx, D, XYZ]
두개의 리스트를 병합하기
mport java.util.ArrayList;
import java.util.List;
public class ExerciseList {
public static void main(String[] args) {
List<String> firstList = new ArrayList<String>();
firstList.add("123");
firstList.add("456");
firstList.add("789");
List<String> secondList = new ArrayList<String>();
secondList.add("111");
secondList.add("222");
secondList.add("333");
// firstList secondList Merge
firstList.addAll(secondList);
System.out.println(firstList);
// secondList thirdList Merge Index
List<String> thirdList = new ArrayList<String>();
thirdList.add("Hello");
thirdList.add("World");
thirdList.addAll(1, secondList);
System.out.println(thirdList);
}
}
[123, 456, 789, 111, 222, 333]
[Hello, 111, 222, 333, World]
리스트의 사이즈를 알아보기
import java.util.ArrayList;
import java.util.List;
public class ExerciseList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
System.out.println(list.size());
list.add("Hello");
list.add("World");
list.add("!!");
System.out.println(list.size());
}
}
0
3
리스트가 비어있는지 확인
mport java.util.ArrayList;
import java.util.List;
public class ExerciseList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
System.out.println(list.isEmpty());
list.add("Hello");
list.add("World");
list.add("!!");
System.out.println(list.isEmpty());
}
}
true
false