[Java] 자료형3 (List)

이용준·2022년 10월 24일
0

Java

목록 보기
6/29

1.리스트

리스트는 배열과 비슷한 자바의 자료형으로 배열보다 편리한 기능을 많이 가지고 있다.

  • 리스트는 배열의 크기가 정해지지 않음 (배열을 크기 고정)
  • 동적으로 변화
  • 가변 자료형의 경우 List를 사용하는 것이 유리

1-1. ArrayList

리스트 자료형에는 ArrayList, Vecotr, LinkedList 인터페이스를 구현한 자료형이 있다.
(➢ 여기서 말하는 List 자료형은 인터페이스이며이는 뒤에서 자세히 다루도록 한다.)

  1. add
  • 리스트에 값 추가하기

    import java.util.ArrayList;
    
    public class simple{
      public static void main(String[] args){
        ArrayList pitches = new ArrayList();
        pitches.add("138");
        pitches.add("129");
        ptiches.add("142");
      }
    }
    
    > ArrayList를 사용하기 위해서는 ArrayList를 먼저 import해야 한다.

    만약 첫번째 위치에 "133"이라는 값을 추가하고 싶다면 위치를 파라미터로 넘겨줘야 한다.

    pitches.add(0,"138");
  1. get
  • 리스트에서 특정 위치의 값 출력하기
    [2번째 값 추출]
    System.out.println(pitches.get(1));
  1. size
  • List 갯수 출력
    System.out.println(pitches.size()); // 3 출력
  1. contains
  • 리스트에 해당 항목 있는지 여부를 boolean으로 출력
    System.out.println(pitches.contains("142")); // true
  1. remove
  • remove 메소드에는 2가지 방식이 있다.
    (이름은 같으나 입력 파라미터가 다름)
    1) remove(객체)
    • 객체 삭제 결과를 리턴한다.(true/false)
      System.out.println(pitches.remove("138")); // true
    2) remove(인덱스)
    • 삭제된 인덱스 값 리턴
      System.out.println(pitches.remove(0)); // 138

1-2. 제네릭스(Generics) <>

  • ArrayList<String> pitches = new Arrayist(<String>);

  • 위 밑줄 친 부분처럼 객체를 포함하는 자료형에 어떤 객체를 포함하는지 명시하는것.

    사용할 객체의 타입을 지정함에 따라 불필요한 형변환 과정 생략 가능

    ArrayList<String> pitches = new String(<>);

    1) 제네릭스 미적용

    ArrayList pitches = new ArrayList();
    pitches.add("138");
    pitches.add("129");
    
    String one = (String) pitches.get(0);  // 형변환 필요
    String two = (String) pitches.get(1);

    ArrayList에 추가되는 객체는 Object 자료형으로 인식되어 별도의 형변환 과정이 필요하다.

    2) 제네릭스 적용

    ArrayList<String> pitches = new ArrayList<>();
    pitches.add("138");
    pitches.add("129");
    
    String one = pitches.get(0);  // 형변환 필요X
    String two = pitches.get(1);

1-3. 다양한 방법으로 ArrayList 만들기

ArrayList의 add 메소드를 사용하면 ArrayList 객체에 요소를 추가할 수 있다.

import java.uitl.ArrayList;

public class Sample{
  public static void main(String[] args){
    ArrayList<String> pitches = new ArrayList<>();  // 제네릭스를 사용한 표현
    pitches.add("138");
    pitches.add("129");
    pitches.add("142");
	  System.out.println(pitches); // [138,129,142] 출력

이미 데이터가 존재할 경우 보다 편하게 ArrayList 생성 가능

import java.util.ArrayList;
import java.util.Arrays;

public class Sample{
  public static void main(String[] args){
    String[] data = {"138","129","142"} // 이미 배열 생성됨
    ArrayList<String> pitches = new ArrayList<>(Arrays.asList(data));
    System.out.println(pitches));
  }
}  

java.util.Arrays 클래스의 asList 메소드를 사용하면 이미 존재하는 문자열 배열로 ArrayList를 생성할 수 있다.
또는 다음과 같이 String 배열 대신 String 자료형을 여러개 전달해 생성할 수 있다.

import java.util.ArrayList;
import java.util.Arrays;

public class Sample{
  public static void main(String[] args){
    ArrayList<String> pitches = new ArrayList<>(Arrays.asList("138","129","142"));
    System.out.println(pitches));
  }
}

1-4.String.join

앞에서 생성한 "138","129","142" 요소로 구성된 ArrayList의 각 요소를 콤마(",")로 구분해 하나의 문자열로 만들 수 있을까?

138,129,142

콤마를 각 요소 중간에 삽입하려면 다음과 같이 코드를 작성해야 한다.

import java.util.ArrayList;
import java.util.Arrays;

public class Sample{
  public static void main(String[] args){
    ArrayList<String> pitches = new ArrayList<>(Arrays.asList("138","129","142"));
    String result = "";
    for (int i=0; i<pitches.size(); i++){
      result += pitches.get(i);
      result += ",";  // 콤마 추가    
    }
	  result = result.substring(0, result.length() - 1); // 마지막 콤마 제거
	  System.out.println(result); // 138, 129, 142 출력
  }
}

위 예시는 요소 사이에 구분자를 끼워넣고 마지막 구분자까지 제거해 하나의 문자열로 만든 것이다. 이처럼 까다로운 작업도 String.join을 사용하면 간단하게 처리할 수 있다.

public class Sample{
  public static void main(String[] args){
	ArrayList<String> pitches = new ArrayList<>(Arrays.asList("138","129","142"));
	String result = String.join(",",pitches);
	System.out.println(result); // 138,129,142 출력
  }                                                
}             

String.join("구분자", 리스트객체)와 같이 사용해 리스트 각 요소에 구분자를 삽입해 하나의 문자열로 만둘 수 있다.
String.join은 다음처럼 문자열 배열에도 사용할 수 있다.

public class Sample{
  public static void main(String[] args){
    String result = String.join(",",pitches);
	  System.out.println(result); // 138, 129, 142 출력
  }
}

1-5.리스트 정렬하기(sort)

"138", "129", "142" 요소로 이뤄진 ArrayList를 순서대로 정렬해보자

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

public class Sample{
  public static void main(String[] args){
    ArrayList<String> pitches = new ArrayList<>(Arrays.asList("138","129","142"));
	  pitches.sort(Comparator.naturalOrder()); // 오름차순 정렬
	  System.out.println(pitches); // [129,138,142] 출력
  }
}
  • 오름차순 : Comparator.naturalOrder()
  • 내림차순 : Comparator.reverseOrder()
profile
뚝딱뚝딱

0개의 댓글