9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Java] String... vs String[] どちらが良いかな? 可変引数と配列

Posted at

String... vs String[] どちらが良いかな? 可変引数と配列

ArgumentsWorkMain.png

可変引数として受け取るか、配列として受け取るか。
どっちも同じ様だけど、どっちがいいんだろうか。

ArgumentsWorkMain.java
public class ArgumentsWorkMain {
	public static void main(String... args) {
		ArgumentsWorkMain me = new ArgumentsWorkMain();

		// test1 は可変引数
		// test1(String str, String... args)
		me.test1("");
		me.test1("a", "a");
		me.test1("a b", "a", "b");
		me.test1("", new String[] {});
		me.test1("a", new String[] { "a" });
		me.test1("a b", new String[] { "a", "b" });
		me.test1("((null))", null);
		// ↑ この null は (String[]) null とみなされるが (String) null にもできる
		me.test1("((null))", (String[]) null);
		me.test1("(null)", (String) null);

		// test2 は配列
		// test2(String str, String[] args)
		me.test2("", new String[] {});
		me.test2("a", new String[] { "a" });
		me.test2("a b", new String[] { "a", "b" });
		me.test2("((null))", null);
		me.test2("((null))", (String[]) null);
		// me.test2("(null)", (String) null); // -> Error
	}

	void test1(String str, String... args) {
		StringBuilder buf = new StringBuilder();

		if (args != null)
			for (String e : args)
				if (e != null)
					buf.append(e).append(" ");
				else
					buf.append("(null)");
		else
			buf.append("((null))");

		if (!str.equals(buf.toString().trim()))
			System.out.println(str + " != " + buf);
	}

	void test2(String str, String[] args) {
		StringBuilder buf = new StringBuilder();

		if (args != null)
			for (String e : args)
				if (e != null)
					buf.append(e).append(" ");
				else
					buf.append("(null)");
		else
			buf.append("((null))");

		if (!str.equals(buf.toString().trim()))
			System.out.println(str + " != " + buf);
	}
}

わざわざ null を渡すことは通常無いよね。

結論:各自好きな方を選べ。

俺は可変引数の方が好きだけどね。

↓こういうコードも書いてるでしょ? いちいち new String[] { } はメンドイ!

import java.util.Arrays;
import java.util.List;
...
	void test3() {
		List<String> list0 = Arrays.asList();
		List<String> list1 = Arrays.asList("a");
		List<String> list2 = Arrays.asList("a", "b");
		List<String> list3 = Arrays.asList(new String[] {"a", "b", "c"});

		test2("", (String[]) list0.toArray());
		test2("a", (String[]) list1.toArray());
		test2("a b", (String[]) list2.toArray());
		test2("a b c", (String[]) list3.toArray());
	}

終わり。

9
9
0

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
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?