| Author |
error with printing ArrayList elements
|
nirjari patel
Ranch Hand
Joined: Apr 23, 2009
Posts: 236
|
|
I am getting following error at command line
C:\Users\nirjari\Desktop\javasourcefiles>javac LineCount.java
LineCount.java:18: array required, but java.util.List< java.lang.String> found
System.out.println(lines[i]);
^
1 error
When I am using "lines.length" instead of "lines.size()" to get number of elements in arrayList lines, I am getting following errors
C:\Users\nirjari\Desktop\javasourcefiles>javac LineCount.java
LineCount.java:17: cannot find symbol
symbol : variable length
location: interface java.util.List< java.lang.String>
for(i=0; i<=lines.length; i++) {
^
LineCount.java:18: array required, but java.util.List< java.lang.String> found
System.out.println(lines[i]);
^
2 errors
Why am I getting these errors ? What needs to be fixed ?
I checked sample codes online and they have used "lines.length" and not "lines.size()". So why is lines.length is not working in here ?
Thanks
|
 |
Mohamed Sanaulla
Bartender
Joined: Sep 08, 2007
Posts: 2925
|
|
As you are using a List- you need to use its get(int index) method to retrieve the elements. You would use lines[i] if lines were an array, but lines is a List so you should be using lines.get(i)
And also length is not a part of the List class. You can check out the documentation for the methods supported by java.util.List.
|
Mohamed Sanaulla | My Blog
|
 |
Anupam Jain
Ranch Hand
Joined: Mar 16, 2010
Posts: 61
|
|
Hello Nirjari,
First thing here that you need to look at and understand is that...
Arraylist is not an Array (Yeah... I know they sound similar, but that's the way they liked it.)
And since they are not same... you can't use lines.length or lines[i] notations, which are spcecific to the Array type.
nirjari patel wrote:
When I am using "lines.length" instead of "lines.size()" to get number of elements in arrayList lines, I am getting following errors
C:\Users\nirjari\Desktop\javasourcefiles>javac LineCount.java
LineCount.java:17: cannot find symbol
symbol : variable length
location: interface java.util.List< java.lang.String>
for(i=0; i<=lines.length; i++) {
^
LineCount.java:18: array required, but java.util.List< java.lang.String> found
System.out.println(lines[i]);
^
2 errors
Why am I getting these errors ? What needs to be fixed ?
I checked sample codes online and they have used "lines.length" and not "lines.size()". So why is lines.length is not working in here ?
Thanks
Also, the code that you refferred online must be either using Array type or (otherwise) would be wrong themselves.
|
SCJP-6.0 OCPJWCD-5.0
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32611
|
|
Anupam Jain wrote:. . . Arraylist is not an Array (Yeah... I know they sound similar, but that's the way they liked it.) . . .
ArrayList is called ArrayList because it uses an array to store its data.
|
 |
 |
|
|
subject: error with printing ArrayList elements
|
|
|