안드로이드 어플을 개발하다보면, DataBase를 사용해야 하는 경우가 간혹있다. 우리가 많이 사용하는 전화번호부, 일정관리 어플, 메시지 프로그램들이 모두가 DB를 자체적으로 사용하고 있는 것들이다.


안드로이드는 프레임웍에서 SQLite를 사용하기 쉽게 제공하고 있다. 그래서 오늘은 정말 정말 정말, 간단한 진짜 아무런 기능이 아직 준비되어 있지 않은 기본적인 Provider의 기본중의 기본 클래스만 만들어서 공유하고자 한다. 이후 DB를 사용하거나, openFile(API 9 GingerBread 부터 지원)과 같은 API를 사용해서 기능을 붙여나가고 진짜 DB를 써야 할 이유가 있을때 적절한 설명과 예제를 공유하도록 하겠지만, 오늘은 정말 기 기초적인 Provider의 껍데기만을 만들어뒀다.


나중에 필요할일이 생기면 그대로 복사해서 필요한 것들 추가하고 바로 사용할수 있게함이 목적이다.


Provider를 만들기 위해서는 AndroidManifest.xml에 provider를 선언해줘야 한다, ContentProvider는 내부적으로 Binder Interface를 통해서 IPC를 지원하고 있다.그래서 Manifest File에 내가 제공하는 provider정보를 명세해주어야지 다른 어플에서도 내가 제공하는 Provider의 Authority로 DB를 접근할수 있게 할수있다.


1. AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hoepisagoodthing.simpleprovider"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="15" />

    <application android:label="@string/app_name"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/AppTheme">
        
        <provider
            android:authorities="com.hopeisagoodthing.simpleprovider"
            android:enabled="true"
            android:exported="true"            
            android:label="Coolkim"
            android:name="com.hopeisagoodthing.simpleprovider.Provider"
            android:syncable="false" >
        </provider>

    </application>

</manifest>




2. Provider와 DataBaseHelper Class

package com.hopeisagoodthing.simpleprovider;

import java.io.File;
import java.io.FileNotFoundException;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.util.SparseArray;

public class Provider extends ContentProvider{
	private static final String TAG="Provider";
	private static final String authority = "com.hopeisagoodthing.simpleprovider";
	private SQLiteOpenHelper dbHelper;
	private SQLiteDatabase db;
	private UriMatcher uriMatcher;
	
	private interface Scheme{
		interface Table{
			static final String NAME="name";
			static final String ADDR="address";
			static final String INTEREST="interest";
		}
		interface Match{
			static final int NAME=1;
			static final int ADDR=2;
			static final int INTEREST=3;
		}		
	}	
	
	private static final SparseArray<Stringgt; tableMap = new SparseArraylt;Stringgt;();
	static{
		tableMap.put(Scheme.Match.NAME, Scheme.Table.NAME);
		tableMap.put(Scheme.Match.ADDR, Scheme.Table.ADDR);
		tableMap.put(Scheme.Match.INTEREST, Scheme.Table.INTEREST);		
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		int 	match 	= uriMatcher.match(uri);
		switch(match){
		case Scheme.Match.NAME:
			break;
		
		case Scheme.Match.ADDR:
			break;
			
		case Scheme.Match.INTEREST:
			break;
			
		default:
			throw new UnsupportedOperationException();			
		}
		
		return db.delete(tableMap.get(match), selection, selectionArgs);		
	}

	@Override
	public String getType(Uri uri) {
		int 	match 	= uriMatcher.match(uri);
		switch(match){
		case Scheme.Match.NAME:
			break;
		
		case Scheme.Match.ADDR:
			break;
			
		case Scheme.Match.INTEREST:
			break;
			
		default:
			throw new UnsupportedOperationException();	
		}
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		int 	match 	= uriMatcher.match(uri);
		switch(match){
		case Scheme.Match.NAME:
			break;
		
		case Scheme.Match.ADDR:
			break;
			
		case Scheme.Match.INTEREST:
			break;
			
		default:
			throw new UnsupportedOperationException();	
		}
		
		long rowId =  db.insert(tableMap.get(match), null, values);
		uri = ContentUris.withAppendedId(uri, rowId);
		getContext().getContentResolver().notifyChange(uri, null);
		return uri;
	}

	@Override
	public boolean onCreate() {
		dbHelper 	= new SimpleDatabaseHelper(getContext());
        db 		= dbHelper.getWritableDatabase();
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

        uriMatcher.addURI(authority, Scheme.Table.NAME, Scheme.Match.NAME);       
        uriMatcher.addURI(authority, Scheme.Table.ADDR,Scheme.Match.ADDR); 
        uriMatcher.addURI(authority, Scheme.Table.INTEREST, Scheme.Match.INTEREST);
       
		return true;		
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		int 	match 	= uriMatcher.match(uri);
		switch(match){
		case Scheme.Match.NAME:
			break;
		case Scheme.Match.ADDR:
			break;
		case Scheme.Match.INTEREST:
			break;
			
		default:
			throw new UnsupportedOperationException();	
		}
		
		return db.query(tableMap.get(match), projection, selection, selectionArgs, null, null, sortOrder);
		
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		int 	match 	= uriMatcher.match(uri);
		switch(match){
		
		case Scheme.Match.NAME:
			break;
		
		case Scheme.Match.ADDR:
			break;
		
		case Scheme.Match.INTEREST:
			break;
			
		default:
			throw new UnsupportedOperationException();	
		}
		
		
		return db.update(tableMap.get(match), values, selection,selectionArgs);
	}
	
	@Override
	public ParcelFileDescriptor openFile (Uri uri,String mode){
		ParcelFileDescriptor fd = null;
		
		String filename = uri.getQueryParameter("filename");
		if(filename == null || filename.isEmpty()){
			throw new UnsupportedOperationException();
		}
		File dir = getContext().getFilesDir();
		if(dir.exists() == false){
			dir.mkdir();
		}
		String filepath = dir.getAbsolutePath()+ "/" +filename;
	    try {
			fd = ParcelFileDescriptor.open(new File(filepath), ParcelFileDescriptor.MODE_CREATE|ParcelFileDescriptor.MODE_READ_WRITE);
		} catch (FileNotFoundException e) {
			Log.e(TAG,"Unable to open file "+ filepath);
		}		
		return fd;		
	}
	
	@Override
	public int bulkInsert(Uri uri, ContentValues[] values) {
		long 	rowId 		= -1;
		int 	count = 0;
		int 	match 	= uriMatcher.match(uri);
			
		db.beginTransaction();
					
		switch(match){
		
		case Scheme.Match.NAME:
			break;
		
		case Scheme.Match.ADDR:
			break;
		
		case Scheme.Match.INTEREST:
			break;
		
		default:
			throw new UnsupportedOperationException();	
		}
		
		for(ContentValues value:values){
			rowId = db.insert(tableMap.get(match), null, value);
			if(rowId > 0 ){
				count++;
			}
		}
		
		db.setTransactionSuccessful();			
		
		db.endTransaction();
		uri = ContentUris.withAppendedId(uri, rowId);
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}
	
	private class SimpleDatabaseHelper extends SQLiteOpenHelper {	
		private static final String DATABASE_NAME = "simple.db";
		private static final int DATABASE_VERSION = 1;
		private static final String NAME_TABLE_CREATE = "CREATE TABLE "
				+ "name" + " (" 
				+ "_id" + " INTEGER PRIMARY KEY AUTOINCREMENT," 
				+ "name" + " TEXT "+");";
		
		private static final String ADDRESS_TABLE_CREATE = "CREATE TABLE "
				+ "address" + " (" 
				+ "_id" + " INTEGER PRIMARY KEY AUTOINCREMENT," 
				+ "address" + " TEXT ," 
				+ "name_id" + " INTEGER " + ");";
		
		private static final String INTEREST_TABLE_CREATE = "CREATE TABLE "
				+ "interest" + " (" 
				+ "_id" + " INTEGER PRIMARY KEY AUTOINCREMENT,"				
				+ "interest" + " TEXT ," 
				+ "name_id" + " INTEGER " + ");";
		
		protected SimpleDatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			try {				
				db.execSQL(NAME_TABLE_CREATE);	
				db.execSQL(ADDRESS_TABLE_CREATE);
				db.execSQL(INTEREST_TABLE_CREATE);
			} catch (Exception e) {
				Log.e(TAG, "onCreate: Exception - " + e.getMessage());
			}
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		}
	}
}

블로그 이미지

커뉴

이 세상에서 꿈 이상으로 확실한 것을, 인간은 가지고 있는 것일까?

,

iOS용 게임을 개발할때 coco2d를 사용했었는데, 잠깐 한들여다본 사이에 cocos2d-x라는 것이 나와서 모든 플래폼에서 게임을 개발할수 있게 아예 cpp로 소스를 전부다 만들어놓은것이 나와있었다.


iOS용은 Objective-C로 되어 있었기 때문에 그냥 빌드할때 프로젝트만 추가해서 빌드하면되었는데, 윈도우에서 Android용 게임을 한번 개발해볼까 하고 cocos2d를 설치할려고 하니 개발환경 설치도 ... 하나의 일이된것 같다. 그래서 정리해둔다...


준비물(정말 아래대로 준비해둬야 한다.) - eclipse,JDK, Android SDK는 설치되어 있다는 가정하에 ..

1. Cygwin(Windows 환경하에서 Linux Build환경을 사용하기 위해서 설치필요)

 -  http://cygwin.com/install.html에서 Setup.exe를 다운받고 실행시키면 된다. 설치 패키지중 Devel,Editor 패키지정도는 install로 바꿔서 설치




2. Customized Android NDK (Native Development Kit)(기본 NDK가 아닌 stl을 지원하는 Crystax의 NDK를 반드시 설치해야 한다.) 

 - http://www.crystax.net/ko/android/ndk/7#download

 - 최신 버전으로 다운받고 압축 풀어두면 됨(이걸 모르고 기본 NDK로 cocos2d-x  빌드하려고 무려 3시간을 낭비 했다 ㅠ.ㅠ)

 - 그리고 빌드중 계속 stl , std:: link에러가 나오면 반드시 prog.android\jni\Application.mk 파일을 열어서 아래와 같이 수정해줘야 한다.

    APP_STL := gnustl_static  -->  APP_STL := stlport_static


3. cocos2d-x  다운로드후 압축 풀기 

 - http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Download


압축을 다 해제하고, 설치를 끝낸 후 디렉토리의 모습







준비는 이제 다 끝났으니, 본격적으로 cocos2d를 사용하기 위해서는 환경설정도 맞춰줘야 되고, cygwin 설정 그리고 project설정을 맞춰줘야 한다.해보자

1. windows에 path 추가

 - 환경변수 설정에서 path에 다음두개를 추가해두기.

 -  D:\Android\android-sdks\tools;D:\cygwin\usr\include


2. cygwin terminal을 열어서 .bashrc 수정

 export PATH=$PATH:/cygdrive/d/Android/android-ndk-r7-crystax-5

 export ANDROID_NDK_ROOT=/cygdrive/d/Android/android-ndk-r7-crystax-5

 export NDK_ROOT=/cygdrive/d/Android/android-ndk-r7-crystax-5   --> 이건 프로젝트 생성하면 설정되지만, 그냥 추가해둠.


3. 수정된 .bashrc 반영

 source ~/.bashrc


4. cocos2d-x 프로젝트 설정 수정

D:\Android\cocos2dx\cocos2d-2.0-x-2.0.4\create-android-project.bat 파일이 안드로이드용 프로젝트를 생성해주는 스크립트(열어서 환경설정변경)

:: modify it to work under your environment  

set _CYGBIN=D:\cygwin\bin

if not exist "%_CYGBIN%" echo Couldn't find Cygwin at "%_CYGBIN%" & pause & exit 4


:: modify it to work under your environment

set _ANDROIDTOOLS=D:\Android\android-sdks\tools

if not exist "%_ANDROIDTOOLS%" echo Couldn't find android sdk tools at "%_ANDROIDTOOLS%" & pause & exit 5


:: modify it to work under your environment

set _NDKROOT=D:\Android\android-ndk-r7-crystax-5


5. Windows cmd 열어서 cocos2d-x 용 안드로이드 프로젝트 생성.

D:\Android\cocos2dx\cocos2d-2.0-x-2.0.4\create-android-project.bat을 실행하면 됨.

자신이 추가해둔 sdk 에 따라서 생성할수 프로젝트 들이 나오는데 그중에 하나를 선택하면 됨 예를 들면 아래 처럼하면 됨



6. cygwin에서 shared library 빌드하기.

자신이 생성한 프로젝트 디렉토리로 가서 build 하기(helloworld로 프로젝트를 만들었다면 아래와 같이 하면 됨)




7. eclipse 에서 작업하기
eclipse에서 위에서 생성한 helloworld 프로젝트를 열면 됨.
에러가 나는 경우는 Java Compiler 가 맞지 않을 경우와 cocos2d-x 라이브러리가 없을때인데 아래와 같이 해결하면 된다.

Java Compiler는 1.6으로 맞춰주고 ....



cocos2d Library가 없다고 에러가 나면.... 아래 lib 폴더를 복사해서 아래 eclipse의 패키지처럼되게 넣으면 된다.






실행해보면~~~~~ 이렇게 나온다. 이제 준비끝.... 아흑,.. 삽질을 좀 했다.



iOS게임으로 만들었던 BlueOcean을 Android에 그대로 포팅해봐야 겠다.

'코딩하고 > C,C++' 카테고리의 다른 글

큰 정수 계산하기  (0) 2016.03.27
OS - Page Fault Simulation(FIFO,LRU,Optimal)  (0) 2012.10.21
자료구조 - 계산기 만들기  (10) 2012.10.12
C언어로 만든 객체  (0) 2012.10.11
자료구조 - 다항식 연산하기  (2) 2012.10.10
블로그 이미지

커뉴

이 세상에서 꿈 이상으로 확실한 것을, 인간은 가지고 있는 것일까?

,

Honey Comb(Android 3)부터 Fragment라는 것이 들어왔는데, 그동안 프로바이더나 네트워크 Sync쪽으로만 너무 일이 몰려있던 바람에 Fragment를 이것 저것 많이 다루지 못했던것 같다.


그래서 정말 진짜,, 기초적으로!!! 나중에 참고할일이 있을때 바로 샘플로 사용하기 위해서 간단하 Activity 하나에 Fragment를 두개를 붙이는 예제를 만들었다.

아무런 내용도 없는 진짜 껍데기만 존재하는 코드라서, 나중에 필요한 부분을 붙여넣을 일이 생길때만 사용하면 된다.





너무 휑~~ 하다. 소스도 역시 내용이 없다, 필요할때 채워서 써야 한다. 


1. Main Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <fragment
        android:id="@+id/fragment1"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        class="com.hopeisagoodthing.fragments.Fragment1" />
    <fragment
        android:id="@+id/fragment2"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        class="com.hopeisagoodthing.fragments.Fragment2" />
</LinearLayout>



2. Fragment1 layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/fragment1"
        tools:context=".MainActivity" />

</RelativeLayout>



3. Fragment2 layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/fragment2"
        tools:context=".MainActivity" />

</RelativeLayout>



4. MainActivity.java

package com.hopeisagoodthing.fragments;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}



5. Fragment1.java

package com.hopeisagoodthing.fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class Fragment1 extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater,
			ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment1, container, false);	

		return v;
	}

}



6. Fragment2.java

package com.hopeisagoodthing.fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment2 extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater,
			ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment2, container, false);		

		return v;
	}

}

블로그 이미지

커뉴

이 세상에서 꿈 이상으로 확실한 것을, 인간은 가지고 있는 것일까?

,

오늘은 심심해서 Android 4.x에 새로 추가된것들에 대해서 보고 있었는데, 그중에 재미난것이 하나 있어서 코딩해볼까?? 하고 eclipse를 열었다.


그런데, 코딩할필요가 없었다.





이유는 아예 AnalogClock view를 지원하고 있다. 좋다!!!! 아무것도 할것 없이 그냥 아래 view 만 추가해주면 모든게 끝난다.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent" >


    <AnalogClock xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@+id/analog"

    android:layout_width="match_parent"

    android:layout_height="match_parent" >

    </AnalogClock>


</RelativeLayout>


'코딩하고 > Android' 카테고리의 다른 글

DB관리하기 - Provider 사용하기  (0) 2012.11.21
Fragment 다루기 (아주 심플하게..)  (0) 2012.11.15
HttpClient 사용하기  (0) 2012.10.25
File Observer 사용하기  (0) 2012.10.21
ActionBar로 Tab 만들기  (19) 2012.10.19
블로그 이미지

커뉴

이 세상에서 꿈 이상으로 확실한 것을, 인간은 가지고 있는 것일까?

,

코드를 읽거나, 코드를 작성하거나 할때, 일단 라인수가 큰 코드, 데이터와 코드가 분리되어 있지 않은 코드들을 보면 나도 모르게 불안해진다. 


마음속 깊은곳에서 "고쳐야돼.. 제거해야해... 줄여야해!!" 하는 소리가 들리는것 같은 기분으로 불안한 상태로 코드를 제대로 작성하거나 읽을수가 없다.


포인터가 사용가능한 C언어류를 사용할때에도 Switch나 if를 많이 쓰게 되면 함수포인터로 테이블을 생성하여 사용하거나 했는데, 자바로 넘어오니 어랏??? 없다. 포인터 같은게...


그래서 interface 와 map을 사용하여 switch - case 들을 제거하여 코딩하고 있다.


제거하면 나중에 좋을까?? 


상황에 따라 다르지만, 일반적으로 코드량을 줄일수 있다. 물론 switch - case로 가장 컴팩트하게 코딩을 할수 있는 경우도 많지만, 보통 case에서 구분되어야 하는 경우의 수를 구분짓기 위해 일단 int 형 구분 값이 고정적으로 들어간다.( case [constant 값] : 이런식으로 코딩을 하니까 )

map에서는 그 구분하는 것을 array의 index를 사용하던, 특정한 키 object를 사용하여 구분짓던 무엇이든지 map을 만들수 있는 방법이면 다 사용가능하다. 그래서 case에 대한 정의를 따로 할 필요가 없다. 키만 구분할수 있게 애초에 입력을 받으면 된다.


그리고, case가 추가되거나 제거될때는 map부분만 수정하고 추가하면 된다, switch를 구분하는 곳에서는 더이상수정할 필요가 없어지게 된다. 

이로 인해 logic을 관리하는 클래스와 case들을 관리하는 class로 구분이 가능하게 된다. Map들만 따로 클래스로 생성해서 나눈다음에 상황에 맞는 Map을 logic으로 올려주도록 하면 switch case가 portable하게 만들어지는 것이다.


학부시절 C언어로 뭔가를 만들어오라는 과제를 할때는 Switch Case를 당연히 사용하곤했었는데, 계속 프로그래밍을 하다보니, if,switch,case등을 계속 추가하게 되는 코드들은 나를 너무 불안하게 만들었다. ㅠ.ㅠ


요즘에는 참여하는 프로젝트에서 누군가가 Switch -case를 쓰면 나도 모르게 ctrl - a , delete를 누르게 된다. @.@


예제 코드는 정말 이런식으로 코딩할리 없겠지만, 어떻게 interface로 case를 구분하는냐에 대한 예제정도로만 봐주면 좋을것 같다.



package com.hopeisagoodthing.removeswitch;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class Main {

	/**
	 * @param args
	 */
	private interface IMethod{
		void method();
	}
	
	private static Map<Integer,IMethod> methodArray= new HashMap<Integer,IMethod>();
	static{
		methodArray.put(1, new IMethod(){
			@Override
			public void method() {
				System.out.println("1");				
			}});
		
		methodArray.put(2, new IMethod(){
			@Override
			public void method() {
				System.out.println("2");				
			}});
		
		methodArray.put(3, new IMethod(){
			@Override
			public void method() {
				System.out.println("3");				
			}});
		
		methodArray.put(4, new IMethod(){
			@Override
			public void method() {
				System.out.println("4");				
			}});
		
		methodArray.put(5, new IMethod(){
			@Override
			public void method() {
				System.out.println("5");				
			}});
		
		methodArray.put(6, new IMethod(){
			@Override
			public void method() {
				System.out.println("6");				
			}});
		
		methodArray.put(7, new IMethod(){
			@Override
			public void method() {
				System.out.println("7");				
			}});
		
		methodArray.put(8, new IMethod(){
			@Override
			public void method() {
				System.out.println("8");				
			}});
		
		methodArray.put(9, new IMethod(){
			@Override
			public void method() {
				System.out.println("9");				
			}});
		
		methodArray.put(10, new IMethod(){
			@Override
			public void method() {
				System.out.println("10");				
			}});
		
		methodArray.put(11, new IMethod(){
			@Override
			public void method() {
				System.out.println("11");				
			}});
		
		methodArray.put(12, new IMethod(){
			@Override
			public void method() {
				System.out.println("12");				
			}});
		
		methodArray.put(13, new IMethod(){
			@Override
			public void method() {
				System.out.println("13");				
			}});
		
		methodArray.put(14, new IMethod(){
			@Override
			public void method() {
				System.out.println("14");				
			}});
		
		methodArray.put(15, new IMethod(){
			@Override
			public void method() {
				System.out.println("15");				
			}});
		
		methodArray.put(16, new IMethod(){
			@Override
			public void method() {
				System.out.println("16");				
			}});
		
		methodArray.put(17, new IMethod(){
			@Override
			public void method() {
				System.out.println("17");				
			}});
		
		methodArray.put(18, new IMethod(){
			@Override
			public void method() {
				System.out.println("18");				
			}});
		
		methodArray.put(19, new IMethod(){
			@Override
			public void method() {
				System.out.println("19");				
			}});
		
		methodArray.put(20, new IMethod(){
			@Override
			public void method() {
				System.out.println("20");				
			}});
		
		methodArray.put(21, new IMethod(){
			@Override
			public void method() {
				System.out.println("21");				
			}});
		
		methodArray.put(22, new IMethod(){
			@Override
			public void method() {
				System.out.println("22");				
			}});
		
		methodArray.put(23, new IMethod(){
			@Override
			public void method() {
				System.out.println("23");				
			}});
		
		methodArray.put(24, new IMethod(){
			@Override
			public void method() {
				System.out.println("24");				
			}});
		
		methodArray.put(25, new IMethod(){
			@Override
			public void method() {
				System.out.println("25");				
			}});
		
		methodArray.put(26, new IMethod(){
			@Override
			public void method() {
				System.out.println("26");				
			}});
		
		methodArray.put(27, new IMethod(){
			@Override
			public void method() {
				System.out.println("27");				
			}});
		
		methodArray.put(28, new IMethod(){
			@Override
			public void method() {
				System.out.println("28");				
			}});
		
		methodArray.put(29, new IMethod(){
			@Override
			public void method() {
				System.out.println("29");				
			}});
		
		methodArray.put(30, new IMethod(){
			@Override
			public void method() {
				System.out.println("30");				
			}});
		
		methodArray.put(31, new IMethod(){
			@Override
			public void method() {
				System.out.println("31");				
			}});
		
		methodArray.put(32, new IMethod(){
			@Override
			public void method() {
				System.out.println("32");				
			}});
		
		methodArray.put(33, new IMethod(){
			@Override
			public void method() {
				System.out.println("33");				
			}});
		
		methodArray.put(34, new IMethod(){
			@Override
			public void method() {
				System.out.println("34");				
			}});
		
		methodArray.put(35, new IMethod(){
			@Override
			public void method() {
				System.out.println("35");				
			}});
		
		methodArray.put(36, new IMethod(){
			@Override
			public void method() {
				System.out.println("36");				
			}});
		
		methodArray.put(37, new IMethod(){
			@Override
			public void method() {
				System.out.println("37");				
			}});
		
		methodArray.put(38, new IMethod(){
			@Override
			public void method() {
				System.out.println("38");				
			}});
		
		methodArray.put(39, new IMethod(){
			@Override
			public void method() {
				System.out.println("39");				
			}});
		
		methodArray.put(40, new IMethod(){
			@Override
			public void method() {
				System.out.println("40");				
			}});
	}
	
	private static void withoutSwitch(int inA)
	{
		inA = inA%40+1;				
		final IMethod method = methodArray.get(inA);
		if(method!=null){
			method.method();
		}
		else
		{
			System.out.println("nothing");
		}		
	}
	
	private static void useSwitch(int inA)
	{
		inA = inA%40+1;
		switch(inA)
		{
		case 1:
			System.out.println("1");
			break;
		case 2:
			System.out.println("2");
			break;
		case 3:
			System.out.println("3");
			break;
		case 4:
			System.out.println("4");
			break;
		case 5:
			System.out.println("5");
			break;
		case 6:
			System.out.println("6");
			break;
		case 7:
			System.out.println("7");
			break;
		case 8:
			System.out.println("8");
			break;
		case 9:
			System.out.println("9");
			break;
		case 10:
			System.out.println("10");
			break;
		case 11:
			System.out.println("11");
			break;
		case 12:
			System.out.println("12");
			break;
		case 13:
			System.out.println("13");
			break;
		case 14:
			System.out.println("14");
			break;
		case 15:
			System.out.println("15");
			break;
		case 16:
			System.out.println("16");
			break;
		case 17:
			System.out.println("17");
			break;
		case 18:
			System.out.println("18");
			break;
		case 19:
			System.out.println("19");
			break;
		case 20:
			System.out.println("20");
			break;
		case 21:
			System.out.println("21");
			break;
		case 22:
			System.out.println("22");
			break;
		case 23:
			System.out.println("23");
			break;
		case 24:
			System.out.println("24");
			break;
		case 25:
			System.out.println("25");
			break;
		case 26:
			System.out.println("26");
			break;
		case 27:
			System.out.println("27");
			break;
		case 28:
			System.out.println("28");
			break;
		case 29:
			System.out.println("29");
			break;
		case 30:
			System.out.println("30");
			break;
		case 31:
			System.out.println("31");
			break;
		case 32:
			System.out.println("32");
			break;
		case 33:
			System.out.println("33");
			break;
		case 34:
			System.out.println("34");
			break;
		case 35:
			System.out.println("35");
			break;
		case 36:
			System.out.println("36");
			break;
		case 37:
			System.out.println("37");
			break;
		case 38:
			System.out.println("38");
			break;
		case 39:
			System.out.println("39");
			break;
		case 40:
			System.out.println("40");
			break;
			
		default:
			System.out.println("nothing");
			break;			
		}
		
	}
	private static final int TOTAL_TRIAL = 20;
	private static final int MAX_LOOP = 20000;
	public static void main(String[] args) {		
		Random urandom = new Random();
		int[] inputs = new int[MAX_LOOP];		
		int[] useSwitchResult = new int[TOTAL_TRIAL];
		int[] withoutSwitchResult = new int[TOTAL_TRIAL];
		
		for(int i=0;i<MAX_LOOP;i++){
			inputs[i] = urandom.nextInt();
		}
		
		
		for(int trial=0;trial<TOTAL_TRIAL;trial++)
		{
			System.gc();
			long start = System.currentTimeMillis();
			for(int a=0;a<500*trial;a++){						
				useSwitch(inputs[a]);
			}
			useSwitchResult[trial] = (int) (System.currentTimeMillis()-start);			
		}
		
				
		for(int trial=0;trial<TOTAL_TRIAL;trial++)
		{		
			System.gc();
			long start = System.currentTimeMillis();		
			for(int a=0;a<500*trial;a++){			
				withoutSwitch(inputs[a]);
			}
			withoutSwitchResult[trial] = (int) (System.currentTimeMillis()-start);
		}
		System.out.println("useSwitch :" );
		for(int trial=0;trial<TOTAL_TRIAL;trial++)
		{
			System.out.print(useSwitchResult[trial]+"\t");
		}
		
		System.out.println("\nwithoutSwitch :" );
		for(int trial=0;trial<TOTAL_TRIAL;trial++)
		{
			System.out.print(withoutSwitchResult[trial]+"\t");
		}				
	}
}



블로그 이미지

커뉴

이 세상에서 꿈 이상으로 확실한 것을, 인간은 가지고 있는 것일까?

,