Page 1 of 1

[HD Pg 352, Sec. 12.4.1 - arraylist-and-collections]

Posted: Thu Apr 25, 2019 12:17 pm
by OCAJO1
al.add("charlie"); //insert an object
al.add(2, "david"); //remove an object
al.remove(0); //process the objects
Although obvious by the code, but maybe the above comments should be adjusted.

Also, a side question to different part of the same code segment,
for(Object o : al){
String name = (String) o;
System.out.println(name+" "+name.length());
}
given the above code,

1. Why the following causes compiler error "variable declaration not allowed here" only when no brackets are present.
for(Object o : al)
String name = (String) o;
2. while, as expected, the following causes no compiler error with or without brackets.
String name = " ";
for(Object o : al)
System.out.println(name+" "+name.length());
Thanks

Re: [HD Pg 352, Sec. 12.4.1 - arraylist-and-collections]

Posted: Thu Apr 25, 2019 10:54 pm
by admin
Added to errata. Thank you for reporting.

1/2. That is just a rule of the Java language. As per JLS 14.14.1., the basic for statement allows "Statement" and "StatementNoShortIf" kind of statements as its body. Definition of "Statement" is given as:
StatementWithoutTrailingSubstatement
LabeledStatement
IfThenStatement
IfThenElseStatement
WhileStatement
ForStatement
As you can notice, it does not include LocalVariableDeclarationStatement.

HTH,
Paul.

Re: [HD Pg 352, Sec. 12.4.1 - arraylist-and-collections]

Posted: Fri Apr 26, 2019 1:01 pm
by OCAJO1
Ok. So as for proper programming, use of brackets alleviates the need for remembering (or worrying about) such rules. But as for the exam, is this rule something that needs memorizing? Thanks

Re: [HD Pg 352, Sec. 12.4.1 - arraylist-and-collections]

Posted: Fri Apr 26, 2019 9:35 pm
by admin
No, not important for the exam.

Re: [HD Pg 352, Sec. 12.4.1 - arraylist-and-collections]

Posted: Tue Jul 27, 2021 1:19 pm
by enthunoob
Printing the names of all the Employees in a list of Employees, computing interest for a list of Accounts, or something as simple as computing the average of a list of numbers, require you do deal with a list of objects instead of one single object.
Spelling mistake: to

Is it worth reporting these here?

Re: [HD Pg 352, Sec. 12.4.1 - arraylist-and-collections]

Posted: Tue Jul 27, 2021 9:19 pm
by admin
>Is it worth reporting these here?
Yes, definitely. All errors reported here will be fixed in the next build.
We sincerely appreciate your feedback.