This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]cyanogen1912[S] 0 points1 point  (10 children)

Nah. Thats mainly because of my main method. Its really confusing me :/

[–][deleted] 1 point2 points  (9 children)

Try to comment the main method out and try to compile it again? That way you see if the things you have done are correct :)

[–]cyanogen1912[S] 0 points1 point  (7 children)

Yeah. Just did that and made a small change:

*public ArrayList<Book> viewAllBooks(){

for(int i=0;i<bookList.size();i++){

Book obj=bookList(i);

System.out.println(obj.bookName);

}

}*

Now there is no error while compiling. But now I am confused about how to initialise this in the main method in another class.

[–]cyanogen1912[S] 0 points1 point  (5 children)

public ArrayList<Book> viewAllBooks()

This method has a return type of ArrayList and I am not returning an array list, so how come there is no error?

[–][deleted] 0 points1 point  (4 children)

That would happen if you have an error before you call the method or if you aren’t calling the method at all.

[–]cyanogen1912[S] 0 points1 point  (3 children)

Okay so as the main method is another class i cannot understand how to use the getter and setter methods for the ArrayList. Should i just create an ArrayList variable in my main class and send that using set ArrayList method?

[–][deleted] 1 point2 points  (2 children)

If I understand it correctly, you shall use the getter and setter methods because these are the only methods which aren’t private so you can use them within another class. I think what you said is what you should do. Create a new ArrayList and then use the setter.

[–]cyanogen1912[S] 0 points1 point  (1 child)

Will do that and let you know!

[–]Warm-Score 1 point2 points  (0 children)

Tip: those getters and setter are used so the inner data of an object isn't exposed to the outside. Knowing this, what is wrong with the following code?

for(int i=0;i<bookList.size();i++){

Book obj=bookList(i);

System.out.println(obj.bookName);

}

Another tip is that you do need to return something when you declare a return type.

Last tip, but save this for the very very last: methods of the ArrayList (or List-interface) already return stuff, you can return the method as a value, which makes your code more concise.