I'm trying to add Objects to ArrayList, during static inputs, it's working fine
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. 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
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
.
At the same time java.util.Scanner
has lots of methods to get values of specific types: nextBoolean()
, nextByte()
, etc.
Also, I would strongly suggest: do not use collections of raw types . Java has pretty good generics mechanism. So, if you are in the process of learning - here is good resource to start.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.