자바 배열 기초

배열(array)는 자바 프로그램에서 자주 사용하는 매우 중요한 개념이다. 배열의 사전적 의미는 '동일한 타입의 데이터가 일정한 순서로 모여 있는 것'을 의미하는데, 자바는 이런 배열을 참조 타입이라는 독특한 형태로 사용한다.

 

배열 객체 생성

new 데이터타입[배열크기];

배열 객체를 생성할 때 가장 먼저 등장하는 것이 new라는 예약어이다. JVM은 new라는 예약어를 만나는 순간 가장 먼저 객체 생서에 필요한 메모리 공간을 확보한다. 이때 중요한 정보가 바로 배열의 데이터타입과 크기이다. 만약 new int[5]; 라고 했다면 int타입(4byte)의 데이터 5개를 저장한다는 의미이므로 정수 5개를 저장할 수 있는 20byte만큼의 메모리 공간이 확보되는 것이다.

 

배열 객체는 생성되는 순간 각 저장 공간에 0부터 시작하는 인덱스 번호가 자동으로 부여되며, 각 인덱스에는 기본값이 자동으로 할당된다. 이를 배열의 기본 초기화라고 한다.

 

배열과 참조 변수

객체지향 언어를 이용하여 프로그램을 개발하면 수많은 객체들이 메모리에 생성되며, 각 객체는 고유한 메모리 주소를 갖는다. 그런데 프로그램에서 객체를 사용하기 위해 객체들의 메모리 위치를 외어서 사용하는 것은 불가능하다.

따라서 메모리 주소를 사람이 기억할 수 있는 참조 변수라는 것에 할당하고, 이 참조 변수를 통해 메모리상의 객체를 사용하는 것이다.

데이터타입[] 참조변수;

예) int[] scoreList;
double[] avgList;
String[] addressList;

 

배열 참조 변수 선언과 관련된 각 요소의 의미는 다음과 같다.

 

데이터 타입: 배열에 저장되는 데이터의 종류를 결정한다.

[] : 배열 첨자라고 읽으며, 현재 변수가 배열 변수임을 의미한다. 이 첨자의 개수에 따라 배열의 차원이 결정된다.

참조변수: 배열 객체의 주소가 할당될 참조 변수의 이름이다.

 

데이터타입[] 참조변수 = new 데이터타입[데이터크기];

int[] scoreList = new int[5];
public class Main {
    public static void main(String[] args) {
        int score = 83;
        int[] scoreList = new int[5];

        System.out.println("기본형 score : " + score);
        System.out.println("참조형 scoreList : " + scoreList);
    }
}

배열의 사용

배열의 참조 변수를 이용하면 배열 객체가 생성된 메모리의 특정 위치까지 접근할 수 있다.

이는 마치 주소를 통해 특정 건물을 찾아가는 과정과 동일하다. 즉, scoreList라는 참조 변수를 이용하면 메모리에 다른 객체가 있다 하더라도 정확하게 scoreList변수가 참조하는 배열객체를 찾아갈 수 있는 것이다.

 

public class Main {
    public static void main(String[] args) {
        int[] scoreList = new int[5];
        scoreList[0] = 76;
        scoreList[1] = 92;
        scoreList[2] = 49;

        System.out.println("scoreList[0] : " + scoreList[0]);
        System.out.println("scoreList[0] : " + scoreList[1]);
        System.out.println("scoreList[0] : " + scoreList[2]);
        System.out.println("scoreList[0] : " + scoreList[3]);
        System.out.println("scoreList[0] : " + scoreList[4]);

    }
}

for(데이터타입 참조변수 : 배열참조변수) {
	반복 수행문;
}
public class Main {
    public static void main(String[] args) {
        int[] scoreList = new int[5];
        scoreList[0] = 76;
        scoreList[1] = 92;
        scoreList[2] = 49;

        for(int score : scoreList) {
            System.out.println(score);
        }

    }
}

728x90

'Language > JAVA' 카테고리의 다른 글

[JAVA] 버블 정렬 알고리즘  (0) 2023.10.18
[JAVA] 참조 변수와 null  (0) 2023.10.18
[JAVA] 이름이 있는 break  (0) 2023.10.18
[JAVA] 데이터 타입 변환  (0) 2023.10.18
[JAVA] 연산자  (1) 2023.10.17

Array.prototype.at(index);

Array.prototype.at(index); method는 parameter로 반환받고 싶은 element의 index값을 넘겨주며, parameter로 음수와 정수 모두 사용가능하며 음수인 경우 배열의 뒤에서부터 indexing한다.

const array = ["apple", "banana", "lemon"];

console.log(array.at(0)); // "apple"
console.log(array[0]); // "apple"

console.log(array.at(-1)); // "lemon"
console.log(array[array.length -1]); // "lemon"

 

Array.prototype.concat(elements);

Array.prototype.concat(elements); method는 기존 배열에 인자로 들어온 요소나 배열을 합하여 새로운 배열을 반환하는 메서드이다.

- 기존 배열을 변경하지 않는다.

- 인자가 추가된 새로운 배열을 반환한다.

const array = ["apple", "samsung"];
const array2 = ["LG"];

console.log(array.concat(array2)); // [ "apple", "samsung", "LG" ]
console.log(array); // ["apple", "samsung"]

const array3 = array.concat(array2);
console.log(array3); // ["apple", "samsung", "LG"]

 

Array.prototype.copyWithin(target, start [,end]);

Array.prototype.copyWithin(target, start [,end]); method는 배열의 일부를 얕게 복사한 뒤, 동일한 배열의 다른 위치에 덮은 후 해당 배열을 반환한다. 이때 배열의 길이는 변경되지 않는다.

const array = ['a','b','c','d','e','f'];
const array2 = ['a','b','c','d','e','f','g'];
array.copyWithin(2,5); // ['a','b','f','d','e','f']
array2.copyWithin(1,2,5); // ['a','c','d','e','e','f','g']

console.log(array); // ['a','b','f','d','e','f']
console.log(array2); // ['a','c','d','e','e','f','g']

 

Array.prototype.entries()

Array.prototype.entries(); method는 배열의 각 인덱스에 대한 키/값 쌍을 가지는 새로운 Array Iterator 객체를 반환한다.

const array = ["apple", "lemon", "orange", "strawberry"];
const iterator = array.entries();

console.log(iterator.next().value)); // [0, "apple"] => Array
console.log(iterator.next().value)); // [1, "lemon"] => Array
console.log(iterator.next().value)); // [2, "orange"] => Array
console.log(iterator.next().value)); // [3, "strawberry"] => Array
console.log(iterator.next().value)); // undefined

 

Array.prototype.every(function)

Array.prototype.every(function) method는 배열의 모든 요소가 주어진 판별함수를 통과하는지 테스트하는 메서드로, 반환값은 boolean이다.

const isTenOver = (element) => element > 10;
const array = [11,12,14,20];

array.every(isTenOver); // true

 

Array.prototype.fill(value [, start [ , end] ] );

Array.prototype.fill() method는 배열의 시작부터 끝 이전까지 정적인 값 하나로 모두 채우는 메서드이다.

* parameter

- value : 배열을 채울 값

- start : 시작 인덱스 기본값 0

- end : 끝 인덱스 기본값 array.length

const array = [1,2,3,4,5];

array.fill(5);
console.log(array); // [5,5,5,5,5]

array.fill('a',2,4); // [5,5,'a','a',5]

 

Array.prototype.filter( callback(element [ , index [ , array ] ] ) [ , thisArg ]);

Array.prototype.filter() 메서드는 매개변수로 주어진 callback 함수의 테스트를 통과한 요소들만 모아 새로운 배열을 반환한다. 

- callback : true 를 반환하면 요소를 유지 false를 반환하면 요소를 버린다. 

- element : 현재 처리할 요소

- index : 현재 처리할 요소의 인덱스

- array : filter를 호출한 배열

- thisArg : callback을 실행할 때 this로 사용하는 값

const number = [1,2,3,"4",5,6];
const newNumber = number.filter( (element) => typeof element === "number" );

console.log(newNumber); // [1,2,3,5,6]

 

Array.prototype.find( callback [ , thisArg ] )

Array.prototype.find() 메서드는 주어진 판별함수를 만족하는 첫 번째 요소의 값을 반환한다. 해당하는 요소가 없다면 undefined를 반환한다.

const array = ["a",3,4,"b"];
const found = array.find((element) => typeof element === "number");

console.log(found); // 3

const fruits = [
	{ name : "banana", quantity : 3 },
    { name : "apple", quantity : 5 },
    { name : "lemon", quantity : 2 }
];

function findApple(fruit){
	return fruit.name === "apple";
}

const Apple = fruits.find(findApple);
console.log(Apple); // {name: 'apple', quantity: 5}

 

Array.prototype.findIndex( callback(element [ , index [ , array ] ]) [ , thisArg ] );

Array.prototype.findIndex() 메서드는 주어진 판별함수를 만족하는 첫 번째 요소의 인덱스를 반환한다. 배열의 첫 번째 요소가 존재하지 않는다면 -1을 반환한다.

const fruits = [
	{ name : "banana", quantity : 3 },
    { name : "apple", quantity : 5 },
    { name : "lemon", quantity : 2 }
];

function findApple(fruit){
	return fruit.name === "apple";
}

function findCherry(fruit){
	return fruit.name === "cherry";
}

const Apple = fruits.findIndex(findApple);
console.log(Apple); // 1

const Cherry = fruits.findIndex(findCherry);
console.log(Cherry); // -1

 

Array.prototype.forEach(callback(currentValue [ , index [ , array ]] ) [ , thisArg ] );

Array.prototype.forEach(); method는 주어진 함수를 배열 요소 각각에 대해 실행한다.

const array = ["apple", "banana", "lemon", "cherry"];
array.forEach( fruit => console.log(fruit) );
// "apple"
// "banana"
// "lemon"
// "cherry"

 

Array.prototype.includes(valueToFind [, fromIndex ]);

Array.prototype.includes(); method는 배열이 특정 요소를 포함하고 있는지를 판별한다. 반환값은 boolean이다.

- valueToFind : 찾고자하는 요소

- fromIndex : 검색을 시작할 위치 

const array = ["apple", "banana", "lemon"];
array.includes("apple"); // true
array.includes("cherry"); // false
array.includes("apple",0); // true
array.includes("apple",2); // false
array.includes("lemon",1); // true

 

Array.prototype.indexOf(searchElement [, fromIndex])

Array.prototype.indexOf(element, [fromIndex]); 메서드는 배열에서 지정된 요소를 찾을 수 있는 첫 번재 인덱스를 반환하고 존재하지 않으면 -1을 반환한다.

const array = [ "a", "b", "c", "d", "e" ];
console.log( array.indexOf("e") ); // 4
console.log( array.indexOf("f") ); // -1
console.log( array.indexOf("a",2) ); // -1

 

Array.isArray(obj);

Array.isArray() 메서드는 메서드의 인자가 Array인지 아닌지를 판별한다. 반환값은 Boolean이다.

const array = [1,2,3];

Array.isArray(array); // true
Array.isArray(3); // false

[ + ] 계속 추가할 예정

Array.prototype.join()

Array.prototype.map()

...

push()

pop()

reduce()

reverse()

shift()

slice()

some()

sort()

unshift()

toString()

values()

 

 

728x90

+ Recent posts