배열을 list타입으로 보여주고 싶을 때 쓴다.
예시 1)
public class AsList{
public static void main(String[] args) throws Exception{
//스트링 배열타입 생성
String[] food = new String[]{"비빔밥","라면","생선"};
//스트링 배열을 리스트 타입으로 보여주기 설정
List<String> list = Arrays.asList(food);
System.out.println("The list is : " + list);
}catch(NullPointerException e){
System.out.println("Exception thrown: " + e);
}
}
The list is : [비빔밥, 라면, 생선]
예시2)
Arrays.asList()로 배열을 리스트 타입으로 받고, 배열값을 합쳐보는 코드이다.
public class MyConcatList {
public static void main(String[] args){
String[] aespa = {"karina","winter"};
ArrayList<String> params = new ArrayList<String>(Arrays.asList(aespa));
String concat = "";
for(int i=0;i<params.size();i++){
if(i+1==params.size()){
break;
}
concat = params.get(i)+""+params.get(i+1);
}
params.add(concat);
System.out.println(params.get(2));
}
}
if(i+1)에서 for문을 빠져나오는 이유는 concat에서 params.get(i+1)로 되었기 때문에 만약 i가 1이 된다면 params.get(1+1)로 되서 out of index에러가 난다.
'Java' 카테고리의 다른 글
Stringbuffer 클래스 (0) | 2022.01.07 |
---|---|
인스턴스 변수, 클래스 변수 , static변수 (0) | 2022.01.07 |
두 변수의 값 바꾸기 (swap) (0) | 2022.01.07 |
Try-catch 예외처리 (0) | 2022.01.07 |
Super() 메소드 (0) | 2022.01.07 |
댓글