[英]ArrayList Objects runtime inputs being treated as Strings
I'm trying to add Objects to ArrayList, during static inputs, it's working fine 我试图将对象添加到ArrayList,在静态输入期间,它工作正常
class ArrayListDemo4
{
public static void main(String[] args)
{
Collection cl = new ArrayList();
cl.add(true);cl.add("Hello");cl.add(6.55f);cl.add(566);
out.println(cl);
for(Object o: cl)
System.out.println(o.getClass());
}
}
Output: 输出:
D:\COLLECTIONS>java ArrayListDemo4
[true, Hello, 6.55, 566]
class java.lang.Boolean
class java.lang.String
class java.lang.Float
class java.lang.Integer
When I'm trying to do the same with runtime inputs, the getClass() is giving only as String. 当我尝试对运行时输入执行相同操作时,getClass()仅以String形式给出。 I noticed that
next()
has 2 signatures with different return types public java.lang.String next(), public java.lang.Object next()
and generalized console input to Object 我注意到
next()
有2个签名,具有不同的返回类型public java.lang.String next(), public java.lang.Object next()
和对象的通用控制台输入
class ArrayListDemo3
{
public static void main(String[] args)
{
Scanner input = new Scanner(in);
List cl = new ArrayList(4);
out.println("Enter the objects to the ArrayList:");
for (int i =0; i < 4; i++ )
{out.print("cl["+i+"] = "); cl.add((Object)input.next()); }
out.println(cl);
for(Object o: cl)
{out.println(o.getClass());}
}
}
Output: 输出:
Enter the objects to the ArrayList:
cl[0] = true
cl[1] = Hello
cl[2] = 6.55f
cl[3] = 566
[true, Hello, 6.55f, 566]
class java.lang.String
class java.lang.String
class java.lang.String
class java.lang.String
Can someone please correct/help me with - how do I get respective Object types for runtime entered values? 有人可以纠正/帮助我-如何获得运行时输入值的相应对象类型?
Consult with java.util.Scanner
javadoc, and you will find that next()
always returns String
. 咨询
java.util.Scanner
javadoc,您将发现next()
始终返回String
。
At the same time java.util.Scanner
has lots of methods to get values of specific types: nextBoolean()
, nextByte()
, etc. 同时,
java.util.Scanner
有很多方法可以获取特定类型的值: nextBoolean()
, nextByte()
等。
Also, I would strongly suggest: do not use collections of raw types . 另外,我强烈建议: 不要使用原始类型的集合 。 Java has pretty good generics mechanism.
Java具有很好的泛型机制。 So, if you are in the process of learning - here is good resource to start.
因此,如果您正在学习中- 这是开始的好资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.