I have two classes, RectNode and RectList. The assignment is to create a list of rectangles (with another class called RectangleA). When I use the tester it seems like all of the nodes are added to the all of lists, even tho I create different lists. For example, the tester creates two lists: rL1
and rL2
. Then it adds one rectangle to the 1st list, and one to the 2nd. The problem is that when I run the tester and prints both lists with a toString()
method I created, it shows that both rectangles are in both of the lists. Can anyone help me find the problem?
When running test:
rL1: The list has 2 rectangles.
- Width=5 Height=7 PointSW=(0,0)
- Width=3 Height=8 PointSW=(0,0)
rL2: The list has 2 rectangles.
- Width=5 Height=7 PointSW=(0,0)
- Width=3 Height=8 PointSW=(0,0)
classes:
public class RectList
{
private static RectNode _head;
public RectList(){
_head = null;
}
public static void addRect(RectangleA r){
if(empty()){
_head = new RectNode(r);
}else{
boolean isThereRectangle = false;
RectNode ptr = _head;
while(ptr.getNext() != null){
if(ptr.getRect().equals(r)){
isThereRectangle = true;
}
ptr = ptr.getNext();
}
if(ptr.getRect().equals(r)){
isThereRectangle = true;
}
if(isThereRectangle == false){
ptr.setNext(new RectNode(r));
}
}
}
public String toString(){
String list = "";
int counter = 0;
if(!empty()){
RectNode ptr = _head;
while(ptr != null){
counter++;
list += (counter + ". " + ptr.getRect().toString() + "\r\n");
ptr = ptr.getNext();
}
}
return ("The list has " + counter + " rectangles." + "\r\n" + list);
}
}
public class RectNode
{
private RectangleA _rect;
private RectNode _next;
public RectNode(RectangleA r){
_rect = r;
_next = null;
}
public RectNode(RectangleA r, RectNode n) {
_rect = r;
_next = n;
}
public RectNode(RectNode r){
_rect = r._rect;
_next = r._next;
}
public RectangleA getRect(){
return new RectangleA(_rect);
}
public RectNode getNext(){
return _next;
}
public void setRect(RectangleA r){
_rect = new RectangleA(r);
}
public void setNext(RectNode next){
_next = next;
}
}
public class test
{
public static void main(String[] args) {
RectList rL1 = new RectList();
RectList rL2 = new RectList();
RectangleA r1 = new RectangleA(5, 7);
RectangleA r2 = new RectangleA(3, 8);
rL1.addRect(r1);
rL2.addRect(r2);
System.out.println("rL1: " + rL1.toString() +"\nrL2: " + rL2.toString());
}
}