LoginSignup
1
2

More than 5 years have passed since last update.

配列の長さを指定しないで、要素を追加していく方法

Last updated at Posted at 2019-06-26

初記事です。来年社会人でIT企業へ入ることが決まり、独学でJavaの勉強をしています。。
超初心者のため、コードなどは参考にならない(汚すぎてよくない)と思います。


配列(int[]など)を使用してArrayListのadd()メソッドのようなことをできないか調べました。

配列の長さを逐一変更していくしかない

みたいです。。

配列の長さを変えるにはSystem.arraycopy()を使って配列のコピーをつくる必要があり、
例えばint[3]からint[5]に変更する場合、


class Hairetsu {
    public static void main(String args[])
    {
        int[] a = new int[3]; //コピー元
        a[0] = 1;
        a[1] = 2;
        a[2] = 3;

        int[] b = new int[5]; //コピー先

        System.arraycopy( a, 0, b, 0, a.length ); //( 配列aを, aの0から, 配列bへ, bの0から, aの要素全ての数分)コピー!

        for ( int i = 0 ; i < b.length ; i++ ){
            System.out.println( b[i] );
        }

    }
}

実行結果


1
2
3
0
0

といったコードになります。
なので、これを応用し、リストにあるadd()メソッド的なものを作ろうとすると、、、

class HairetsuList {

    static int[] list;

    public static void add(int a){

        int i = list.length;
        int[] copy = new int[i+1]; //元より要素数が1おおきい配列を作成

        System.arraycopy( list , 0 , copy , 0 , i );

        copy[i] = a ;
        list = copy; //配列の長さ違うけど、これありなんだ。。

    }
}

こんな感じになり、一応テスト、、

class Test {
    public static void main(String args[])
    {
        HairetsuList test = new HairetsuList();
        test.list = new int[0];

        test.add(4);
        test.add(5);
        test.add(3);

        System.out.print("{ ");
        for (int i=0 ; i < test.list.length; i++){
            System.out.print( test.list[i]+" ");
        }
        System.out.print("}");
    }
}

実行結果


{ 4 5 3 }

コードの稚拙さはともかく、何とかなりました。普通にリストなどを使えばいいですね。。
今回は企業の研修課題で配列を使わなくてはならないとあったため頑張って考えましたが、、プログラミング難しい。。

1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2