Java Array/Arraylist

SeokYoung·2021년 11월 11일
0

내가 자주 쓰는 Array / Arraylist

배열(Array)이란?

"인덱스"에 대응하는 데이터들로 이루어진 연속적인 자료구조
"변수"들의 아파트라고 생각하면 편함

변수란..데이터가 들어갈 수 있는 메모리 공간!


import java.util.Arrays; // 임포트 해줘야 사용 가능


        //String 배열 생성
        String[] stringArray = new String[5];

        // int 배열을 선언과 동시에 초기화
        int[] intArray = new int[] {1,3,2,5,4};


	// 정수값 출력X, 주의!
        System.out.println(intArray); 	
        
        // 문자열 변환 후 출력!
        System.out.println(Arrays.toString(intArray));	// [1, 3, 2, 5, 4]
        
        //for_each, 반복문과  Array는 거의 같이 사용됨
        for (int i: intArray){		
            System.out.print(i+" ");	// 1 3 2 5 4
        }	
        //배열의 길이
      	System.out.println(intArray.length);	// 5
        
        // 배열 오름차순 정렬
        Arrays.sort(intArray); 
        System.out.println(Arrays.toString(intArray));	//[1, 2, 3, 4, 5]
               

Arrays 클래스의 메소드들


사용법 확인하러 가기


그런데..
처음 생성할 때 크기를 선언해 줘야 하는게 상당히 불편하다..
크기가 유동적이라면, Arraylist를 자주 쓰는 편.

Arraylist 란?

크기가 변하는 배열!

	int[] intArray = new int[]{1, 2, 3, 4, 5};
        String[] stringArray = new String[]{"one", "two", "three", "four", "five"};

        ArrayList<Integer> intList = new ArrayList<Integer>();	// Integer 타입의 리스트 생성
        var arrList = new ArrayList<Integer>();	// 이런 식으로도 리스트 생성 가능!

        //int 타입 배열 -> Integer 리스트, add()
        for (int i : intArray) {
            intList.add(i);
        }
        // String 배열 -> String 리스트, Arrays.asList()
        ArrayList<String> stringList = new ArrayList<>(Arrays.asList(stringArray));
        
        //리스트 요소의 총 개수, size()
        System.out.println(intList.size()); // 5
        System.out.println(stringList.size()); //5
		
        // 전체 출력
		for (int i : intList) {
            System.out.print(i + " ");  //1 2 3 4 5
        }

        // 이런식으로도 가능!, get()
        for (int i = 0; i < 5; i++) {
            System.out.print(intList.get(i) + ":");
            System.out.print(stringList.get(i) + " ");	//1:one 2:two 3:three 4:four 5:five
        }
        
        //오름차순 정렬, Collections 클래스
        Collections.sort(stringList);   // five four one three two
        
        //요소 중간에 더할 수 있다!
        stringList.add(0,"apple");	// apple five four one three two
        stringList.add(5,"banana");	// apple five four one three banana two 
        
        //뒤집기
	Collections.reverse(stringList);	//two banana three one four five apple    
        
        //특정 인덱스 찾기, indexOf()
        int index1 = stringList.indexOf("three");	// 2
        int index2 = intList.indexOf(3);	// 2
        
        //리스트 -> 배열
        String[] arr = stringList.toArray(new String[stringList.size()]);

Arraylist 메소드

profile
부뚜막 위에 먼저 올라간 조용한 개발자

0개의 댓글

관련 채용 정보