I'm still new to Java, and get a bit lost sometimes implementing simple stuff.
I am writing a class that defines an array, and needs to have two constructors, one that takes no parameters and creates an empty list, and another that takes the name of a text file as a parameter and creates a list containing the numbers listed in the text file.
I have also added a method that adds a new number to the list at any time. However, I need a boolean method that returns 'true' if the list contains the given number and 'false' otherwise. The problem is, I'm not sure how to implement this correctly.
Also, how do I construct a toString method that will return a string representing the numbers in the list.
You'd be better using an ArrayList rather than an array. These can grow dynamically and there are methods for adding to the end or at a specific point, so you wouldn't need to maintain a reference to the next insertion point, you wouldn't need to read your file twice and you wouldn't need to allocate such a large array to start with. Take at a look at the javadoc and come back if you're not sure of anything.
Joined: Nov 06, 2005
Thanks for the help. I shall have a look at that appraoch and get back to you if there are any further problems.
First, note that the word "List" has a specific meaning in Java. It is an interface implemented by classes such as ArrayList and LinkedList. There is no List in this code (and whether that's a good choice is another issue), so to avoid confusion you might want to call this something else.
With respect to your boolean "contains" method, I'll suggest 2 approaches:
Use the java.util.Arrays class to sort and search your array. (See the API.)
Write your own code to iterate through the array and test each element for equality to the test value.
With respect to the toString method you describe, you basically need to iterate through the array and concatenate each element. The best way to do this (especially given the size of your array) is to use a StringBuffer or StringBuilder. (See the API.)
(Please use CODE tags, and please don't cross-post.) [ November 10, 2005: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Joined: Nov 06, 2005
Thanks for all the advice. I'm sorry for cross-posting. Won't happen again!!