java/자료형

List 추가정리

appmaster 2019. 7. 9. 14:30

List 자료형에는 ArrayList, LinkedList등의 List 인터페이스를 구현한 자료형이 있다. 여기서 말하는 List 자료형은 인터페이스인데 인터페이스에 대해서는 나중에 다루기로 한다.

 

 

add

박찬호 선수가 총 3번의 투구를 138, 129, 142(km)의 속도를 던졌다면 다음과 같이 코드를 작성할 수 있다.

ArrayList pitches = new ArrayList();
pitches.add("138");
pitches.add("129");
pitches.add("142");

add 라는 메소드를 이용하여 투구 스피드를 저장함.

만약 첫번째 위치에 "133"이라는 투구 스피드를 삽입하고 싶다면 아래와 같이 코딩하면 된다.

pitches.add(0,"133");

 

get

System.out.println(pitches.get(1));

ArrayList의 get 메소드를 이용하면 특정 인덱스의 값을 추출할 수 있다.

 

 

size

size메소드는 ArrayList의 갯수를 리턴한다. 현재 pitches에 담긴 갯수에 해당되는 값이 출력될 것이다.

System.out.println(pitches.size());

 

contains

contains 메소드는 리스트 안에 항목값이 있는지를 판별하여 그 결과를 boolean으로 리턴한다.

System.out.println(pitches.contains("142"));

142라는 값을 포함하고 있으므로 true가 출력될 것이다.

 

 

remove

remove 메소도에는 2개의 방식이 있다.(이름은 같지만 입력파라미터가 다르다.)

1. remove(객체)

2. remove(인덱스)

 

remove(객체)의 경우는 리스트에서 객체에 해당되는 항목을 삭제하고 삭제한 결과를 리턴한다.

System.out.println(pitches.remove("129"));

true

"129"라는 항목이 성공적으로 삭제되고 true를 리턴한다.

 

 

remove(인덱스)의 경우는 해당 인덱스의 항목을 삭제된 항목으로 리턴한다.

System.out.println(pitches.remove(0));

138

pitches의 첫번째 항목은 "138"이므로 "138"이 삭제된 후 "138"을 리턴했다.

 

 

 

다음은 테스트에 사용되었던 모든 코드이다.

import java.util.ArrayList;

public class TestList {
    public static void main(String[] args) {
        ArrayList<String> pitches = new ArrayList<String>();
        pitches.add("138");
        pitches.add("129");
        pitches.add("142");

        System.out.println(pitches.get(1));
        System.out.println(pitches.size());
        System.out.println(pitches.contains("142"));

        System.out.println(pitches.remove("129"));
        System.out.println(pitches.size());
        System.out.println(pitches.remove(0));
    }
}

 

 

ArrayList를 함수로 호출해서 사용하는 방법은 이러하다. 참고하라.

import java.util.ArrayList;

public class Test{
	
	public static void main(String a[]) {
		
		        ArrayList<Integer>first = new ArrayList<>();
		        ArrayList<Boolean>second = new ArrayList<>();

		        for(int i =0; i<10; i++) {
		            first.add(i);
		        }

		        for(int i =0; i<first.size(); i++){
		            if(first.get(i)<5){
		                second.add(true);
		            }
		            else {
		                second.add(false);
		            }
		        }

		        System.out.println(first);
		        System.out.println(second);
		        System.out.println();
		        
		        
		        System.out.println(howmanyodds(first));

	}
	
	public static int howmanyodds(ArrayList<Integer> list) {
		int result = 0;
		for(int i =0; i<list.size(); i++){
			if(list.get(i) %2 ==1) {
				result++;
			}
		}
		return result;
	}
}

'java > 자료형' 카테고리의 다른 글

배열의 특징 추가  (0) 2019.07.16
자바 ArrayList  (0) 2019.05.25
(자바) 배열값 복사 & 복제  (0) 2019.04.24
자바 ArrayList  (0) 2019.04.08
자바 자료형의 종류  (0) 2019.04.08