2011년 4월 29일 금요일

자바의 배열(Array)

자바에서 배열(Array)이란 리스트 혹은 집합 같은 개념으로 같은 종류끼리 모아놓은 것이라고 생각하면 될 것이다. 여러분이 재미있는 게임이나 사진 혹은 음악 자료들을 다운받아서 게임이나 음악은 장르별로 사진은 장소나 시간으로 디렉토리를 분류해서 보기 쉽도록 모아놓지 않는가? 프로그래밍에서도 배열을 사용하는 이유는 똑같이 자료들을 효율적으로 관리해서 보다 빠르게 찾기 위함이다.

배열([ ])은 int,double,char,boolean타입등의 자료형 배열과 클래스 같은 String타입등의 객체형 배열로 나뉘어지고 이밖에도 1차원 배열, 2차원 배열, 3차원 배열등 배열의 배열을 원하는데로 만들수 있는 길이 열려있다. 즉, 배열을 만든 상태(1차원)에서 요소별로 또 배열(2차원)을 만들고 다시 거기서 배열(3차원)을 만들고 이런식으로 계속해서 배열을 만드는 것이 가능하다. 자바에서는 이를 다차원 배열이라고 부른다.

그럼 여기서 배열은 어떻게 사용하는지를 본격적으로 알아보자. 배열은 자신이 어떤 타입인지 일단 선언 즉 초기화시켜 주어야 하고 그 다음에 배열을 만들기 위한 메모리 공간을 new 라는 키워드를 통해 생성해서 얼마만큼의 공간을 확보할지 알려주어야 한다. 그리고 생성된 배열에 넣기위한 요소들을 추가해 가는 것이 자바에서 배열을 만드는 요체라 할수 있겠다.

객체 생성을 할때 new 라는 키워드를 사용한다고 예전에 잠시 배운바 있다. 거기서 우리가 추리할수 있는바는? 그렇다.^^ 배열도 객체이기 때문에 new 를 사용할수 있는 것이다. 객체에 대한 내용은 다음에 클래스와 메소드에 관한 내용을 다룰때 자세히 설명할 것이니 너무 걱정하지 말고 지금은 배열에만 집중하기 바란다. 그럼 배열을 공식으로 한번 써보면 이와 같다.

배열종류[ ] 배열이름=new 배열종류[배열길이];

일단 정수 int 타입을 통해 알기쉽게 정리해 보겠다.


int[ ] a;
int a[ ];

배열을 어떤 타입으로 할것인지 초기화(선언)시키고 있는데 위의 두가지 방식으로 표현할수 있다. 당연한거지만 중간에 띄워쓰기 같은 것은 자바에서 인식하지 않으니 항상 염려하지 말기 바라며 이제 이 부분은 앞으로도 더이상 언급하지 않겠다.ㅎㅎ 자바에서 어디서나 가장 많이 쓰이는 방식은 첫번째 방식이고 이를 사용하는 것을 추천한다. 아무래도 두번째보다는 첫번째 표현이 배열이라는 것을 자료타입을 보자마자 바로 판단이 가능해서 보편적으로 쓰인다.

a=new int[3];

다음 단계는 배열을 new를 통해 생성시키는 단계이다. 또한 공간은 3을 주어 3가지 요소를 넣을 준비를 하게 만드는 과정이다. 이 과정을 다른 변수 초기화처럼 배열도 아래와 같이 한줄로 쓸수 있다.

int[ ] a=new int[3];

이제 정수타입을 저장할수 있는 공간 세군데를 확보하였으니 관련 자료형에 대한 값을 넣어주면 배열이 완성된다. 아직은 관련값을 넣어주지 않은 상태인데 자바에서 관련값을 넣기 이전인 지금, 이제 막 완성된 배열의 요소들(a[0],a[1],a[2])은 자동적으로 0이 세팅된다. 그런 까닭에 일반 변수들은 초기화시키지 않고 즉 관련값을 넣지 않고 출력시키면 에러가 나지만 배열은 초기화(initialize)시키지 않고 배열 요소들을 출력해도 에러없이 자동세팅된 0을 출력한다. 믿어지지 않으면 직접 실험해보기 바란다.^^

이제 관련값을 배열에 넣어보겠다

a[0]=1;
a[1]=2;
a[2]=3;

index 즉 공간의 지점은 항상 0부터 시작한다. 본 강이의 자바 강좌를 빠지지 않고 열공한 이들이라면 그 이유(?)에 대해서 이미 인지하고 있을 것이다. 위처럼 긴 과정(?)을 거칠 필요없이 아래처럼 짧게 선언할수도 있다.

int[ ] a=new int[ ]{1,2,3};
int[ ] a={1,2,3};

자바에서 배열을 초기화시키는 방법인데 위의 두가지 중 아무거나 사용가능하나 첫번째 방식이 더 명확하므로 이를 추천한다. 표현방식만 다를뿐이지 자바에서 인식해서 읽어드리는 과정은 똑같다. 

지금은 배열의 길이가 길지않아 관련값을 출력하는게 힘들지 않지만 값이 10개나 20개 혹은 그 이상이라면 어느 세월에 배열 요소들을 다 출력할수 있을까? ㅎㅎ 인덱스와 관련값이 일정한 크기로 증가하고 있다. 증감연산자가 떠오르지 않는가? 이럴때 써먹으라고 우리가 저번에 열심히 반복문에 대해서 배운 것이다. 뛰어난 프로그래머는 정신적으로는 부지런해야하지만 몸은 게을러야한다.ㅎㅎ 어떤 의미인지는 여러분이 알것이라 믿고 조금더 설명하겠다.

배열이름.length

배열의 길이를 알수 있는 명령어다. 배열의 길이를 알아야 반복문을 쓰더라도 언제 중지할지 그 기준을 만들수가 있다. for문의 조건문을 떠올리면 왜 필요한지 이해하리라 본다. 위의 예제에서는 길이를 알려면 배열명인 a를 이용해 아래와 같이 쓰면 될것이다.

a.length

위의 length는 배열을 완성하면 언제든지 배열의 길이를 알수 있도록 자바에서 만들어놓은 명령어이다. 밑의 그림은 인덱스([?])가 0부터 9까지인 길이 10의 배열인데 9번째 값은 배열공간 [8]에 들어간다는 것을 말한다. 배열의 지점인 인덱스는 항상 0부터 시작하니까 말이다. 이 부분 때문에 많은 이들이 자바의 배열을 어려워하는 것이나 알고보면 별것 아니다.^;


자 그럼 흥미로운 아래 예제(?)를 통해서 배열을 어떻게 만들고 배열의 길이는 어떻게 써먹는지 보기로 하자. 예제의 내용은 이러하다. 아이돌 가수로 유명한 아이유가 방송사에 나가기전 점검을 위해 소속사에서 3가지 테스트를 보았다. 물론 아이유를 비롯 소속사에 속해 있는 모든 가수들이 이 테스트를 치뤘다. 보컬, 율동, 의상에 한해 분류별로 점수를 매겼는데 아이유의 경우 보컬은 98점, 율동은 91점, 의상은 83점이 나왔다. 다른 가수들과의 빠른 비교를 위해 총점과 평균점수가 필요한데 이것을 해결하기 위한게 우리의 사명(?)이다.


가수 아이유의 테스트 결과

Total=272점
Average=90.0점

수고하셨습니다.
테스트를 우수한 성적으로 통과하였습니다.

위의 예제를 컴파일하고 실행하면 위와 같은 결과가 나올 것이다. 프로그램이 조금 긴듯하지만 자바의 제어문을 이미 공부한 여러분들은 배열 이외에는 별 어려운 사항은 없을 것이다. 그럼 프로그램을 분석해 보자. 처음에 배열 공간 3개를 초기화하고 생성하는 과정이다. 총점(sum)과 avg(평균)은 int과 double타입으로 선언하였다. 생성된 배열공간에 획득한 점수를 차례대로 입력하였다. for문을 통해 총점을 계산하고 iu.length를 통해 평균을 계산하였다. iu.length가 얼마(3)인지는 당연히 알것이지만 몰라도 된다. 이것은 자바에서 배열을 만들면 자동으로 계산하기 때문이다. 여기서 / 표시는 나누라는 뜻이고 컴퓨터에서 연산기호는 덧셈+, 뺄셈-, 곱하기*, 나누기/, 나머지% 로 표시한다. 다음에 결과를 출력하는데 if문을 통해 90점 이상이면 통과 메세지를 그 미만이면 else구문을 통해 재도전 메세지를 추가적으로 표시하도록 만들었는데 테스트에서 아이유는 90점을 받아 가까스로 위기를 모면하고 있는 프로그램이다.ㅎㅎ

예제를 보면서 한가지 아쉬움이 남을 것이다. 우리가 공부하는 입장이므로 시간 절약하기 위해서 저렇게 미리 테스트값을 넣고 프로그램을 돌리지만 현실에서는 테스트 할때마다 매번 다시 코드를 수정해야하는 것에 번거로움을 느낄 것이다. 필자는 이런 상황을 미리 예견(!)하고 유저한테서 입력값을 받을수 있는 방법을 여러 각도로 조명한바 있다. 키보드로 입력값(테스트 점수)을 받아서 테스트 결과를 출력하는 예제를 여러분의 힘으로 한번 만들어 보기 바란다. 배열을 이용한 한편의 작품이 될것이다. 작품 이름은 "아이유 컨디션 테스트" ^^ 항상 그렇지만 프로그램을 본인이 만든것과 비교하기를 희망하는 이들을 위해 본 프로그램을 아래에 올린다. 시도도 해보지 않고 바로 답만 보는 악의 무리들(?)이 없기를 바라고 코드가 이해되지 않는다면 입출력에 관련된 강이의 예전 자바강좌를 보면 다시 기억이 날것이니 설명은 생략하겠다.


이번엔 객체형 배열을 설명할텐데 어떻게 쓰는지 사용방법을 기술해 보겠다.

String[ ] s;
s=new String[3];

String[ ] s=new String[3]

따로 쓰던 같이 쓰던 상관없다. 선언하고 생성하는 과정은 같다. 여기서 여러분은 이런 궁금증이 생길 것이다. 자바의 객체형 배열에서는 관련값을 넣기 이전에 무엇으로 세팅이 될까? 일반 자료형 배열인 숫자같은 정수형 타입이 아니니 0 대신에 null 이 자동으로 세팅되도록 만들어져 있다. null은 객체가 참조하는 곳이 없을때 즉 자기 자신만 홀로서기(?)하고 있을때 null이라는 표현을 쓴다.(객체에 관해서는 후에 더 자세히 거론하겠다.)

자바에서는 왜 배열 요소들을 자동으로 세팅하게 만들었을까? 배열 요소가 한두개가 아니라 수십개라고 생각해 보라. 그런데 관련값은 현재 수십개중에 몇개밖에 넣을게 없는 상황이라면 어떻게 하겠는가? 만약 배열이 자동으로 초기화되지 않는다면 배열 요소들의 일부만 쓰더라도 프로그램을 정상적으로 컴파일하고 작동시킬려면 남아있는 배열 요소들에 0이나 null값을 일일이 넣어주는 수고(?)를 해야할 것이다. 이런 수고를 덜어준 자바(?)에게 우리는 경의를 표해야 할 것이다. 일동 경례~ ㅎㅎ

자료형에 객체형 타입이 들어갔을뿐 배열을 생성하는 과정은 보다시피 다를게 없다. 허나 관련값을 넣어주는 방식이 다르니 아래를 주의깊게 보기 바란다.

s[0]=new String("아이유");
s[1]=new String("카라");
s[2]=new String("소녀시대");

String[ ] s={new String("아이유"), new String("카라"), new String("소녀시대")};

String[ ] s=new String[ ]{new String("아이유"), new String("카라"), new String("소녀시대")};

세가지 중 아무거나 써도 되지만 첫번째나 세번째 방식이 클리어하므로 될수 있으면 이중에서 쓰도록 하자. 특히 괄호와 따옴표를 틀리지 않도록 주의해서 쓰기 바란다. 객체형 배열은 어떤 식으로 사용해야 되는지 이제 감이 올것이다. 위의 세가지 방식 모두 예제를 통해 잘되는지 직접 실행해 보기 바란다.


세가지 방식을 각각 group, title, member라는 배열명을 통해 제대로 작동되는지 프로그램을 만들어 본것이다. 게으름 피우지 말고 직접 코드 쳐가면서 걸그룹과 만나는 시간(?)을 가져보기 바란다. 실행을 하면 결과값은 아래와 같을 것이다.

가수이름: 아이유
노래제목: 좋은 날
멤버수: 한명

가수이름: 카라
노래제목: 루팡
멤버수: 다섯명

가수이름: 소녀시대
노래제목: 훗
멤버수: 아홉명

오늘은 배열이 어떤 상황에서 유용하게 쓰이는지를 몸소 체험(?)했을줄 믿는다. 다음 시간에는 배열 중에서도 2차원이나 그 이상의 다차원 배열에 대해서 공부해 보도록 하겠다. 이번 시간에 배운 배열을 확실하게 정립하면 다차원 배열을 공부하는데 훨씬 수월할 것이다. 그럼 다음 시간을 기약하면서 오늘 강좌는 여기서 마치겠다.^^

댓글 37개:

  1. 배열에 대해서 이제야 정리가 되네요~ 이런 좋은 사이트가 있었다니 증말 감사해용~~

    답글삭제
  2. int[] number = {1,2,3,4,5,6,7};

    특정 상황에서만 6, 7을 사용하고싶은데 잘 안되네요 ㅠ

    답글삭제
  3. 잘보았습니다~ 감사합니다 ㅎ

    답글삭제
  4. Hi, I desire to subscribe for this webpage to get newest updates, thus where
    can i do it please help.

    Feel free to visit my blog post ... Discount savings

    답글삭제
  5. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically
    tweet my newest twitter updates. I've been looking
    for a plug-in like this for quite some time and was hoping maybe you would
    have some experience with something like this.
    Please let me know if you run into anything. I truly enjoy reading your
    blog and I look forward to your new updates.

    My web site :: office furniture online

    답글삭제
  6. Interesting blog! Is your theme custom made or did you download
    it from somewhere? A design like yours with a few simple tweeks would really
    make my blog stand out. Please let me know where you got your
    design. With thanks

    Also visit my weblog: office furniture Western Cape

    답글삭제
  7. Hey I know this is off topic but I was wondering if you
    knew of any widgets I could add to my blog that automatically tweet my newest twitter updates.
    I've been looking for a plug-in like this for quite some time and was hoping maybe you would
    have some experience with something like this.
    Please let me know if you run into anything. I truly
    enjoy reading your blog and I look forward to your new updates.


    Also visit my page: office furniture Western Cape

    답글삭제
  8. Wіtɦ havin so muich content and articles
    do youu ever run into any prfoblems of plagorism or copyright infгingement?

    My website haas a lot of exclusive content I'ѵe eitber written myself or outsourced buut it loοks like
    a lot of it is popping it up all ovdr the weЬb without myy
    permission. Do you know anyƴ ways to help prevent contgеnt from being stolen?
    I'd certainly appreciɑte it.

    Τake a look at my рage; general pain rеlief ()

    답글삭제
  9. I’m not that mսch оf a inteгnet reaԁer tߋ be honest but your blogs reаlly nice, kеep it
    up! I'll go ahead and ƅookmark your website to come bаck later on. Cheers

    my blog :: pain relievers

    답글삭제
  10. cеrtainly ljke yοur weƅ site ƅut yoս have to
    test the sƿelling on several of your posts.
    Many of them are rife with ѕpеlling problems and I too find іt very bothеrsome to tell
    thee truth on the other haznd I will certaіny come again again.

    Heree is my webѕite uit pain

    답글삭제
  11. I am actually grateful to the holder of this web site
    who has shared this enormous article at at this place.


    my blog Music marketing books

    답글삭제
  12. Thank you for any other informative blog. The place else
    may I get that kind of info written in such an ideal
    means? I have a challenge that I'm just now running on, and I've been on the
    glance out for such information.

    Also visit my web-site - best web hosting best blog sites for writers

    답글삭제
  13. During a normal chair and abc aare guaranteed that operations would never be denied.
    I can recall, Evenflo has aabc issued a recall of 1.
    Parents in 2011 that will not always have the contemporary French chairs.
    Now I'm like, featuring the metal stripping for you to adjust the chair is American Eastern's principal.


    Feel free to surf to my blog :: stół rozkładany (http://hdwallpaper2.com/profile/elcampion)

    답글삭제
  14. І do not even know the way I finished up here, howevеr I thought this post useɗ to be great.
    I do not recognize who yoou might bbe but certainly you're
    ging too a well-known blogger if you aren't already.
    Cheers!

    my sіte; relief opiate-based pain

    답글삭제
  15. Ηi! Do you know if they make any plugins to protect against hackers?
    I'm kinda paгɑnoiԀ aЬout losing еverything I'ѵe worked hard on. Any tips?



    My webpagе; health tips

    답글삭제
  16. Іtss like you learn mmy thoughts! You apƿeаr
    to grasp ѕo much apρгoximately this, like you wrotye the
    ebook in it or sometɦіng. I feel that you simply can do with a few p.c.

    to power the messsage house a bit, but instead of that, this is fantasic
    blog. A great read. I will definitely bе back.


    Feel free to viѕit my homepage :: tmj exercises

    답글삭제
  17. I аm truly pleased to glance at thiѕ weblog posts which carrіes tons of useful information, thanks
    for providing these kіnds of data.

    my web page :: removal company reading

    답글삭제
  18. If you are going for most excellent contents like me, only go to see this web page all the time as it offers quality contents, thanks

    Feel free to visit my site - Market Samurai Review

    답글삭제
  19. If you are in the UK, the show is usually aired on E4 or you can watch it at.
    Drinking adequate amount of water also helps in keeping your
    pouts hydrated. Silky lingerie helps them to be more sexy and comfortable with
    their partner.

    Visit my blog post; omg ราคา

    답글삭제
  20. Thesе are genuinely enormouѕ ideas in regarding blogging.
    Уou hae touchеԁ some fastidious factors here. Any
    waay keep up wrinting.

    My weblog - natural resources

    답글삭제
  21. ңey excellent blog! Does running a Ƅlog like this take a massive amunt
    work?I have absolutely no knoledge oof coding bսt I had been hoping to start mmy own blog ѕoon. Anyway, should you hаve anyy recommendаtions
    or tips for new blog owneгs pleasе share.
    I undwrstаnd this is off suƄject however I sіmoly had to ask.
    Thank you!

    Take a look at my page; fish oil arthritis

    답글삭제
  22. 8by drmiddlebrook241 followersThe job market, as well. When houses were
    getting abc less than $500. Youu may have been the biggest-named franchisor
    annd investor visas, these pens to the recycling
    process, generally that's a word or phrase.
    As long as you are making a generous valuation. Wheen I catch them, it is not all,
    do not enjoy. Dr Jason Hickel lectures at the last minute
    and finally, countermeasures.

    My blog program do faktur (www.awardwinningwebdesign.com)

    답글삭제
  23. An even faster system is currently being installed in Israel.
    Broadly, radio controlled boats come in three different types of packages; RTR kits, ARTR kits,
    and Assembly kits. This will provide various sites that offer online jobs
    for such skills.

    Have a look at my weblog; produits veterinaires en ligne

    답글삭제
  24. His fourth point is your business school, vehicle and
    profit I can. This allows you to always establish the contact details given in the marketplace.
    Now I'm going to put $200, 000 yen that's just over 53K per year.


    Here is my homepage - worek bokserski

    답글삭제
  25. Do you have a spam issue on this blog; I also am a
    blogger, and I was curious about your situation; many of us have created some nice methods and we are looking
    to trade strategies with others, why not shoot me an e-mail if interested.


    Feel free to surf to my blog post gold plating

    답글삭제
  26. Bouffant: It is a very classy hairdo and was amongst the
    most popular bridal hairstyles 2011. It will also search extraordinary on hair which is thick with wealthy hues
    and highlights all over the strands. Some finishing wax applied very
    lightly and you will have perfect sedu celebrity
    hairstyles every time.

    Look at my blog :: hairstyle finder

    답글삭제
  27. Hello, Neat post. There's an issue with your website in web explorer, might test this?
    IE nonetheless is the marketplace leader and a huge section of other people will pass over your magnificent writing due to
    this problem.

    Look at my page :: free movie download

    답글삭제
  28. To check that they are balanced, there are several tactics that you can use.
    It also is able to work with Zero Turning Radius models. Use about two table spoons of new lawnmower oil and evenly
    work it over the filter to gently layer it.

    Visit my web site :: Small Engine Repair Edmonton

    답글삭제
  29. The Kohler twin-cylinder engines have reduced noise, less vibration and are easy starters.
    Toro's Attach-a-Matic hitch system makes changing attachments quick and easy.
    IT and Telecommunication related Equipments ' These include computers, printers, laptops, notebooks, telephones, electronic typewriters, answering machines, calculators, fax machine, telex, copiers, and so forth.


    Here is my web blog - Lawn Mower Repair

    답글삭제
  30. With older lawn mowers, it can also be fairly simple
    to fix and gaze after it to make it last, but with the newer garden mowers it
    can be very stressful as technology has traveled forward by leaps and bounds.
    It also is able to work with Zero Turning Radius models.

    Transport materials around your yard with the 10 cu ft or the 17 cu ft poly cart.


    Take a look at my homepage :: Lawn Mower Repair

    답글삭제
  31. You do not need to have this professionally done if you have the parts and a lawn
    mower jack to lift up the vehicle and perform engine work underneath.
    With technological advances, the rate at which electronics are thrown away
    has increased to such an extent that an average 4% of European municipal waste comes
    from electronics and more dangerously, the rate of this waste
    is increasing three times faster than any other waste.
    Their durability and excellent workmanship makes secondhand Toro
    lawnmowers and garden tractors good buys.


    Feel free to surf to my site - Small Engine Repair Edmonton

    답글삭제
  32. Step Five - Change the spark plug while you change the oil
    once a year. This machine was invented in the year of 1827 in Gloucestershire by Edwin
    Budding. You must make certain you purchase the right size for the model with lawn mower you possess.


    Here is my blog post; Lawn Mower Repair

    답글삭제
  33. With older lawn mowers, it can also be fairly simple to fix
    and gaze after it to make it last, but with the newer
    garden mowers it can be very stressful as technology has traveled forward by leaps and bounds.
    It also is able to work with Zero Turning Radius models.

    Transport materials around your yard with the 10 cu ft or the 17 cu ft poly cart.


    my web blog - Lawn Mower Repair

    답글삭제
  34. Even if the product as a whole is no longer useful, the parts
    may still be in working condition, and therefore,
    can be retrieved and reused. If that belt, for instance, is too long or
    too short people mower won't be capable of
    operate correctly. IT and Telecommunication related Equipments ' These include computers, printers, laptops, notebooks,
    telephones, electronic typewriters, answering machines, calculators, fax machine, telex, copiers, and
    so forth.

    Also visit my webpage; Lawn Mower Repair

    답글삭제
  35. Thanks for eѵeгy other wonderful poѕt.
    Thee рlacе elsе may just anyоne gеt thаt type of
    info inn ѕuсh an ideal approach of writіng?
    I haνe a pгesentаtion ѕubѕequent weeκ,
    and I am on the sеarch for suсhinfo.

    My web pagе; physician

    답글삭제
  36. 첫 번째 문제 혼자 풀고 있었는데.. 못 풀것을 알고 있었죠? ㅠㅠ Integer.valueOf()도 안가르쳐 주고.... 혼자 한 시간 허비했음.

    답글삭제