搜尋此網誌

2016年6月19日 星期日

【Java】Copy array

ref:
http://www.programcreek.com/2015/03/system-arraycopy-vs-arrays-copyof-in-java/
http://openhome.cc/Gossip/JavaEssence/EqualOperator.html
http://toyangel.pixnet.net/blog/post/27163971

可以使用
int[] newArray = Arrays.copyOf(oldArray,newArray length);

那它和System.arraycopy()有何差別
可以參考以下範例:


System.arraycopy()
int[] arr = {1,2,3,4,5};
 
int[] copied = new int[10];
System.arraycopy(arr, 0, copied, 1, 5);//5 is the length to copy
 
System.out.println(Arrays.toString(copied));
Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]
Arrays.copyOf()
int[] copied = Arrays.copyOf(arr, 10); //10 the the length of the new array
System.out.println(Arrays.toString(copied));
 
copied = Arrays.copyOf(arr, 3);
System.out.println(Arrays.toString(copied));
Output:
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
[1, 2, 3]





以下廢言,因為有這些錯誤,所以才特別筆記了這一篇。
--------------------------------------------------------------------------------
之前犯了低級錯誤,浪費不少時間。

依照記憶寫的,原本想要複製陣列:
很直覺就寫下
old array =xxxx;
new array = old array
當然這省略一些步驟加上這只是pseudo code而以。
所以想當然爾,每次old array改變時,new array也會跟著改變。(因為new array 是指向 old array的reference value → call by value)


2016年6月12日 星期日

【Android】Autoincrement VersionCode with gradle extra properties

ref:
http://stackoverflow.com/a/21405744
https://github.com/commonsguy/cw-omnibus/tree/master/Gradle/HelloVersioning


down voteaccepted
I would like to read the versionCode from an external file
I am sure that there are any number of possible solutions; here is one:
android {
    compileSdkVersion 18
    buildToolsVersion "18.1.0"

    def versionPropsFile = file('version.properties')

    if (versionPropsFile.canRead()) {
        def Properties versionProps = new Properties()

        versionProps.load(new FileInputStream(versionPropsFile))

        def code = versionProps['VERSION_CODE'].toInteger() + 1

        versionProps['VERSION_CODE']=code.toString()
        versionProps.store(versionPropsFile.newWriter(), null)

        defaultConfig {
            versionCode code
            versionName "1.1"
            minSdkVersion 14
            targetSdkVersion 18
        }
    }
    else {
        throw new GradleException("Could not read version.properties!")
    }

    // rest of android block goes here
}
This code expects an existing version.properties file, which you would create by hand before the first build to have VERSION_CODE=8.