Inicialización del array de cadenas como parámetro constructor [duplicar]
Esta pregunta ya tiene una respuesta aquí:
En Java, es completamente legal inicializar una matriz de cadenas de la siguiente manera:
String[] s = {"FOO", "BAR"};
Sin embargo, cuando se intenta crear una instancia de una clase que toma una matriz de cadenas como parámetro, la siguiente pieza de código NO es permitido:
Test t = new Test({"test"});
Pero esto funciona de nuevo:
Test t = new Test(new String[] {"test"});
¿Puede alguien explicar por qué es esto?
29
Author: Hermann Hans, 2010-12-14
3 answers
String[] s = {"FOO", "BAR"};
Esto solo se permite en el momento de la declaración
No puedes
String[] s;
s={"FOO", "BAR"};
44
Author: Jigar Joshi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-14 06:25:14
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-14 06:25:14
Porque Type[] x = { ... }
es una sintaxis de inicialización para matrices. El { ... }
se interpreta de una manera específica solo en ese contexto específico.
5
Author: Karl Knechtel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-14 06:27:22
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-14 06:27:22
Para que desee una forma sencilla de pasar una matriz de cadenas, le sugiero que use varargs
class Test {
public Test(String...args);
}
// same as new Test(new String[] { "test", "one" })
Test t = new Test("test", "one");
3
Author: Peter Lawrey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-14 07:54:00
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-14 07:54:00