[java] Objects in Java - a beginner

Started by
11 comments, last by cordel 15 years, 3 months ago
okay I'll be more specific.
Like I said before I have a 10 cell array , and each cell has 2 fields - one for Triangles and the other for Rectangles.
A rectangle defined by two points (two x,y) and triangle by three points (three x,y).

how can I define an array that each cell has two fields ,the 'x' would be of type Triangle ,the 'y' - type Rectangle.

For now I've seperated the problem into 2 different arrays ,
Quote:
public ShapeContainer() {
arrrec=new Rectangle[INIT_SIZE];
arrtri=new Triangle[INIT_SIZE];
}

I want to use one array of [10] when the 1st field (x) would be of type Triangle,and the 2nd (y) of type Rectangle.is it possible ? thank you
Advertisement
Quote:Original post by cordel
I want to use one array of [10] when the 1st field (x) would be of type Triangle,and the 2nd (y) of type Rectangle.is it possible ? thank you

The best way would be to have an array of a new class, which had both a triangle and a rectangle as a member. Something like:

public class Pair{  public Rectangle rect;  public Triangle tri;}public class ShapeContainer{  private Pair[] allPairs; // Array of 'Pair' objects  public ShapeContainer()  {    allPairs = new Pair[INIT_SIZE]; // Create empty array of Pair objects    for (int i=0; i<allPairs.length; i++)    {      allPairs = new Pair(); // Create a Pair object in each slot of the array    }  }  public void add(Rectangle r, Triangle t)  {    for (int i=0; i<allPairs.length; i++)    {      // Is this slot used?      if (allPairs.rect == null && allPairs.tri == null)      {        allPairs.rect = new Rectangle(r);        allPairs.tri = new Triangle(t);        break;      }    }  }}


Although instead of having a fixed size array and having used and unused slots you may want to consider using ArrayList which is a resizable array and would make your code simpler.

Also 'Pair' is a fairly rubbish name - again you've been very vauge and it's not obvious what exactly you're trying to do. There's probably a much better name you could pick depending on what the rectangle/triangle pair is supposed to represent.
OrangyTang ,thank you very much (and also to the rest of you guys)
I'll check both ways and see which one is more preferable.

This topic is closed to new replies.

Advertisement