티스토리 뷰

Java 자료구조

1) Array 배열

산도리 2022. 7. 18. 10:58

* 타 블로그 글이 아닌 독학을 통해 이해한 내용을 작성한 것이기 때문에 , 지적은 성대히 환영합니다 ! *

 

 

 

먼저 Array

 

 

Array 배열




 

파이썬으로 알고리즘 공부를 하면서 체계적이진 않지만 한번 훑은 적이 있었다. 그렇지만 인강을 들으면서 좀더 자세히 이해를 해보려 한다.

 

 

 

배열(Array) 은 선형구조 로 이루어져 있다. 선형구조란 나열 되어있는 데이터 간의 관계가 1대1 인 것을 말한다. 또한

 

물리적인 위치와 논리적인 위치가 같다. 이 말은 ,  자료들이 한 줄로 나열되어 있을 때 , 첫번째 자료 다음엔 두번째 자료 

 

가 있다는 물리적인 위치와 , 실제로 자료가 위치해 있는 논리적인 위치가 같다는 말이다. 배열 자료구조의 장점은 그러한 

 

위치가 정확히 정해져있기 때문에 검색, 탐색등을 할 때 매우 빠르고 비용이 적게 든다는 것이다. 하지만 이 배열안에 값을

 

중간에 넣거나 뺄 때의 비용은 높은 편이다. 추후에 더 깊게 공부한다면 시간복잡도에 대하여 포스팅 하겠다.

 

자바의 jdk 클래스 안에는 ArrayList 나 Vector 등의 라이브러리가 존재 하지만 어떤식으로 배열 자료구조가 이루어 지는지

 

코드를 통해 알아 보겠다.

 

 

public class MyArray {

	int[] intArr;   	//int array
	int count;  		//개수
		
	public int ARRAY_SIZE;
	public static final int ERROR_NUM = -999999999;
	
	public MyArray()
	{
		count = 0;
		ARRAY_SIZE = 10;
		intArr = new int[ARRAY_SIZE];
	}
	
	public MyArray(int size)
	{
		count = 0;
		ARRAY_SIZE = size;
		intArr = new int[size];
	}
	
	public void addElement(int num)
	{
		if(count >= ARRAY_SIZE){
			System.out.println("not enough memory");
			return;
		}
		intArr[count++] = num;
				
	}

	public void insertElement(int position, int num)
	{
		int i;
		
		if(count >= ARRAY_SIZE){  //꽉 찬 경우
			System.out.println("not enough memory");
			return;
		}
		
		if(position < 0 || position > count ){  //index error
			System.out.println("insert Error");
			return;
		}
		
		for( i = count-1; i >= position ; i--){
			intArr[i+1]  = intArr[i];        // 하나씩 이동
		}
		
		intArr[position] = num;
		count++;
	}
	
	public int removeElement(int position)
	{
		int ret = ERROR_NUM;
		
		if( isEmpty() ){
			System.out.println("There is no element");
			return ret;
		}
		
		if(position < 0 || position >= count ){  //index error
			System.out.println("remove Error");
			return ret;
		}
		
		ret = intArr[position];
		
		for(int i = position; i<count -1; i++ )
		{
			intArr[i] = intArr[i+1];
		}
		count--;
		return ret;
	}
	
	public int getSize()
	{
		return count;
	}
	
	public boolean isEmpty()
	{
		if(count == 0){
			return true;
		}
		else return false;
	}
	
	public int getElement(int position)
	{
		if(position < 0 || position > count-1){
			System.out.println("검색 위치 오류. 현재 리스트의 개수는 " + count +"개 입니다.");
			return ERROR_NUM;
		}
		return intArr[position];
	}
	
	public void printAll()
	{
		if(count == 0){
			System.out.println("출력할 내용이 없습니다.");
			return;
		}
			
		for(int i=0; i<count; i++){
			System.out.println(intArr[i]);
		}
		
	}
	
	public void removeAll()
	{
		for(int i=0; i<count; i++){
			intArr[i] = 0;
		}
		count = 0;
	}
}

 MyArray 클래스 안에는 요소(자료)를 배열 끝에 추가하는 addElement , 배열 중간에 추가하는 insertElement , 중간 요소

 

를 지우는 removeElement , 모든 요소를 지우는 removeAll 등의 메서드가 들어가 있다. 클래스의 멤버변수 count는 요소의

 

개수를 뜻하며 눈여겨 볼 파트는 insert 파트와 remove 파트다.

 

 

InsertElement

배열에 요소를 넣어보겠다 . 예를 들어 배열에 1,2,3,4,5 가 있고 2와3 사이에 10을 넣고 싶을 땐 3부터 5까지 차례대로 한칸씩 오른쪽으로 땡겨주어 공간을 만들어 주고 그 다음에 2 와 3 사이에 공간이 생기면 10 을 넣어주면 된다 .  

 

 

RemoveElement

배열에 있는 요소를 지우고 싶을 땐 , 삭제 할 특정위치를 그 다음 요소가 덮어써주는 형식으로 코드를 작성해주면 된다.

쉽게 말해 오른쪽 요소가 왼쪽으로 이동하는 모양새다.

 

public class MyObjectArray {

	private int cout;
	private Object[] array;
	public int ARRAY_SIZE;
	
	public MyObjectArray()
	{
		ARRAY_SIZE = 10;
		array = new Object[ARRAY_SIZE];
	}
	
	public MyObjectArray(int size)
	{
		ARRAY_SIZE = size;
		array = new Object[ARRAY_SIZE];
	}
	
	

	
	
	
}

 

 

public class MyArrayTest {

	public static void main(String[] args) {

		MyArray array = new MyArray();
		array.addElement(10);
		array.addElement(20);
		array.addElement(30);
		array.insertElement(1, 50);
		array.printAll();
		
		System.out.println("===============");
		array.removeElement(1);
		array.printAll();
		System.out.println("===============");
			
		array.addElement(70);
		array.printAll();
		System.out.println("===============");
		array.removeElement(1);
		array.printAll();
		
		System.out.println("===============");
		System.out.println(array.getElement(2));
		
	}
}