可变参数:
public static void foo(String... string_array) { ... }
Run Code Online (Sandbox Code Playgroud)
与
单阵列参数:
public static void bar(String[] string_array) { ... }
Run Code Online (Sandbox Code Playgroud)
Java 1.6似乎接受/拒绝以下内容:
String[] arr = {"abc", "def", "ghi"};
foo(arr); // accept
bar(arr); // accept
foo("abc", "def", "ghi"); // accept
bar("abc", "def", "ghi"); // reject
Run Code Online (Sandbox Code Playgroud)
假设上述是真的/正确的,为什么不总是使用varargs而不是单个数组param?似乎免费增加了一点来电灵活性.
专家是否可以共享内部JVM差异(如果有)?
谢谢.
简单的问题,如何使这段代码工作?
public class T {
public static void main(String[] args) throws Exception {
new T().m();
}
public // as mentioned by Bozho
void foo(String... s) {
System.err.println(s[0]);
}
void m() throws Exception {
String[] a = new String[]{"hello", "kitty"};
System.err.println(a.getClass());
Method m = getClass().getMethod("foo", a.getClass());
m.invoke(this, (Object[]) a);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
class [Ljava.lang.String;
Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
Run Code Online (Sandbox Code Playgroud) Java varargs实现中似乎存在一个错误.当方法使用不同类型的vararg参数重载时,Java无法区分适当的类型.
它给了我一个错误 The method ... is ambiguous for the type ...
请考虑以下代码:
public class Test
{
public static void main(String[] args) throws Throwable
{
doit(new int[]{1, 2}); // <- no problem
doit(new double[]{1.2, 2.2}); // <- no problem
doit(1.2f, 2.2f); // <- no problem
doit(1.2d, 2.2d); // <- no problem
doit(1, 2); // <- The method doit(double[]) is ambiguous for the type Test
}
public static void doit(double... ds)
{
System.out.println("doubles");
}
public static void doit(int... is)
{
System.out.println("ints"); …Run Code Online (Sandbox Code Playgroud) 我看到了一个问题:从数组中创建ArrayList
但是,当我使用以下代码尝试该解决方案时,它并不适用于所有情况:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class ToArrayList {
public static void main(String[] args) {
// this works
String[] elements = new String[] { "Ryan", "Julie", "Bob" };
List<String> list = new ArrayList<String>(Arrays.asList(elements));
System.out.println(list);
// this works
List<Integer> intList = null;
intList = Arrays.asList(3, 5);
System.out.println(intList);
int[] intArray = new int[] { 0, 1 };
// this doesn't work!
intList = new ArrayList<Integer>(Arrays.asList(intArray));
System.out.println(intList);
}
}
Run Code Online (Sandbox Code Playgroud)
我在这做错了什么?代码不应该intList = new ArrayList<Integer>(Arrays.asList(intArray));编译得很好吗?
我想知道是否有一种简单,优雅和可重用的方法将字符串和字符串数组传递给期望varargs的方法.
/**
* The entry point with a clearly separated list of parameters.
*/
public void separated(String p1, String ... p2) {
merged(p1, p2, "another string", new String[]{"and", "those", "one"});
}
/**
* For instance, this method outputs all the parameters.
*/
public void merged(String ... p) {
// magic trick
}
Run Code Online (Sandbox Code Playgroud)
即使所有类型都是一致的(String)我也找不到告诉JVM 压扁 p2并将其注入合并参数列表的方法?
此时,唯一的方法是创建一个新数组,将所有内容复制到其中并将其传递给该函数.
任何的想法?
根据您的建议,这里是我将使用的通用方法:
/**
* Merge the T and T[] parameters into a new array.
*
* @param type the …Run Code Online (Sandbox Code Playgroud) 电子邮件只会发送到String[] to阵列中的最后一个电子邮件地址.我打算发送到添加到阵列的所有电子邮件地址.我怎样才能做到这一点?
public void sendMail(String from, String[] to, String subject, String msg, List attachments) throws MessagingException {
// Creating message
sender.setHost("smtp.gmail.com");
MimeMessage mimeMsg = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true);
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "425");
Session session = Session.getDefaultInstance(props, null);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(msg + "<html><body><h1>hi welcome</h1><body></html", true);
Iterator it = attachments.iterator();
while (it.hasNext()) {
FileSystemResource file = new FileSystemResource(new File((String) it.next()));
helper.addAttachment(file.getFilename(), file);
}
// Sending message
sender.send(mimeMsg);
}
Run Code Online (Sandbox Code Playgroud) 是否有一种简洁,惯用的方式(可能使用Apache Commons)来指定OpenOption的常见组合 StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING
我正在读这个答案,它说的是
另请注意,使用显式数组参数调用泛型vararg方法可能会默默地产生与预期不同的行为:
Run Code Online (Sandbox Code Playgroud)public <T> void foo(T... params) { ... } int[] arr = {1, 2, 3}; foo(arr); // passes an int[][] array containing a single int[] element
类似的行为在这个答案得到解释3:
Run Code Online (Sandbox Code Playgroud)int[] myNumbers = { 1, 2, 3 }; System.out.println(ezFormat(myNumbers)); // prints "[ [I@13c5982 ]"Varargs仅适用于引用类型.自动装箱不适用于基元数组.以下作品:
Run Code Online (Sandbox Code Playgroud)Integer[] myNumbers = { 1, 2, 3 }; System.out.println(ezFormat(myNumbers)); // prints "[ 1 ][ 2 ][ 3 ]"
我尝试了更简单的例子:
private static <T> void tVarargs(T ... s)
{
System.out.println("\n\ntVarargs ==========");
System.out.println(s.getClass().getName());
System.out.println(s.length);
for(T i …Run Code Online (Sandbox Code Playgroud) 考虑一个字符串.
String Str = "Entered number = %d and string = %s"
Run Code Online (Sandbox Code Playgroud)
让我们说我有一个对象列表
List<Objects> args = new ArrayList<Objects>();
args.add(1);
args.add("abcd");
Run Code Online (Sandbox Code Playgroud)
有什么方法可以将这些args替换成Str,这样我就能获得一个像"Entered number = 1 and string = abcd "?
通过概括,我计划将所有问题和参数转储到文件(如json)中,并在运行时执行它们.如果有更好的方法,请告诉我.
为什么这样做可行?:
String f = "Mi name is %s %s.";
System.out.println(String.format(f, "John", "Connor"));
Run Code Online (Sandbox Code Playgroud)
这不是吗?:
String f = "Mi name is %s %s.";
System.out.println(String.format(f, (Object)new String[]{"John","Connor"}));
Run Code Online (Sandbox Code Playgroud)
如果方法String.format采用vararg对象?
它编译好但是当我执行它时,String.format()将vararg对象作为单个唯一参数(数组本身的toString()值),因此它抛出一个MissingFormatArgumentException,因为它无法与第二个字符串说明符匹配(%S).
我怎样才能使它工作?在此先感谢,任何帮助将不胜感激.
java ×10
arrays ×2
string ×2
collections ×1
email ×1
formatting ×1
generics ×1
nio ×1
nio2 ×1
overloading ×1
reflection ×1
spring ×1