Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

New ArrayList Problem

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I have to questions regarding ArrayList
1. the get method has the signature as follows:
Object get(int index)
Why is it not neccessary to cast Object to integer
like (System.out.println((Integer)lst.get(i-1))?
Why ist lst.set(5, new Integer(1000) setting the 1000 to 6th
element and not to 5th element?


Interesting is that when I want to calcultate with lst.get(i-1) like shown in the code
As follows then I get this error:

C:\Java\EigeneJavaProgramme>javac TestArrayList.java
TestArrayList.java:24: operator + cannot be applied to int,java.lang.Object
sum += lst.get(i-1);
^

 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Thomas Markl:
1. the get method has the signature as follows:
Object get(int index)
Why is it not neccessary to cast Object to integer
like (System.out.println((Integer)lst.get(i-1))?

Because there is a System.out.println(Object o) method, which will call String.valueOf(o), which will polymorphically call o.toString() on non-null objects. Therefore, in the above case, the return value of Integer.toString() will be printed, which is exactly what you want.

Why ist lst.set(5, new Integer(1000) setting the 1000 to 6th
element and not to 5th element?

Because indices of Lists (as well as arrays) are zero-based.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic