Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:有没有办法将字符串放入列表中<;整数>;?_Java - Fatal编程技术网

Java:有没有办法将字符串放入列表中<;整数>;?

Java:有没有办法将字符串放入列表中<;整数>;?,java,Java,面试问题: 字符串对象可以是任何格式,不仅可以是数字表示。是的,由于类型擦除,可以使用强制转换,但这是一个坏主意™并且这样做后以正常方式使用列表的代码将抛出ClassCastException 但这是可能的,因为这段代码运行: List<Integer> l = new ArrayList<Integer>(); ((List)l).add("hello"); List ilist=new ArrayList();ilist.add(“aString”) List<

面试问题:


字符串
对象可以是任何格式,不仅可以是
数字
表示。

是的,由于类型擦除,可以使用强制转换,但这是一个坏主意™并且这样做后以正常方式使用列表的代码将抛出
ClassCastException

但这是可能的,因为这段代码运行:

List<Integer> l = new ArrayList<Integer>();
((List)l).add("hello");

List ilist=new ArrayList();ilist.add(“aString”)
List<Integer> l = new ArrayList<Integer>();
((List)l).add("hello");
System.out.println("Added successfully");

Iterator it = l.iterator();              // Old-fashioned raw iterator works
while (it.hasNext()) {
    System.out.println(it.next());
}

for (Object o : l) {                     // Enhanced for with Object works
    System.out.println(o);
}

for (Integer i : l) {                    // But this throws when it reaches the
    System.out.println(i);               // String, because String cannot be cast
}                                        // to Integer