|
-
Apr 27th, 2001, 11:44 AM
#1
Thread Starter
Lively Member
Beginner: Dynamic arrays -- without losing values
I'm currently taking my first Java class so bear with me.
The question actually reads: "Create a method to add and
subtract objects".
I assume this means I need to create an array and resize it when
the user wants, preserving the existing values.
---------------------
In Visual Basic it's:
'The next statement resizes the array and erases the elements.
Redim MyArray(10) ' Resize to 10 elements.
'The following statement resizes the array but does not erase
'elements.
Redim Preserve MyArray(15) ' Resize to 15 elements &
'keep existing values.
----------------------
How would I do this with Java?
I apologize for putting a school question here but I can't find
the answer in the text book.
Thanks in advance,
rlb_wpg
-
Apr 27th, 2001, 06:17 PM
#2
I think they are asking you to write the Vector class (java.util.Vector ?). I think you can look at the api code, but I can't check now. Perhaps your custom class should include an Object array "Object[]" and an integer type to keep track of the allowed size of the object array; and getters and setters to maintain the rules for the size, and adding and removing your objects.
You did try it yourself before checking for the answer in the textbook, right?
-
May 1st, 2001, 02:57 PM
#3
Thread Starter
Lively Member
Unfortunately, the back of the book doesn't have answers.
As it turns out, they wanted us to create an object with the length
of two objects.
ie.
public myObject Add(myObject obj2)
{
return new myObject(this.length + obj1.length);
}
...
obj3 = obj1.Add(obj2);
...
The way it was written was so confusing.
Thanks for your input!
-
May 1st, 2001, 06:41 PM
#4
Dazed Member
You could if you wanted to use a LinkedList. Which by definition would be: "A collection of ordered objects".
All it is, is a data structure where each element refrences the next element in the list. A doubly linked list is where each element refrences bolth the previous and the next element in the list.
You can use the ListIterator ie.... java.util.ListIterator;
which supports bidirectional iteration of lists. so in effect you can
go back a forth and add and delete elements as you like.
import java.util.*;
class linkedlistExample{
public class void main(String [] args){
LinkedList list = new LinkedList();
list.add("Hello");
list.add("my");
list.add("name");
list.add("is");
list.add("Brandon");
list.display(list);
}
private void display(LinkedList list){
System.out.println("The size of the list is: " + list.size());
ListIterator i = new ListIterator(0);
while(i.hasnext()){
Object o = i.next();
if(o == null){
System.out.println("null");
}
System.out.println(o.toString());
}
}
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|