Search code examples
javavectorarraylistmultidimensional-arrayrelational

2-dimensional object that can grow in java


I need to associate a unique key with each of a number of rectangle objects in Java. The key is in double data type, and the rectangles are obviously rectangle data types.

Currently, I have the rectangles in a vector, but they are not of much use to me unless I can also access their keys, as specified in the first paragraph above.

I would make a 2d array, with the first column being the key and the second column being the rectangle, but the number of rows in the array will need to change all the time, so I do not think an array would work. I have looked into vectors and arrayLists, but I am concerned about being able to search and slice the data.

Can anyone show me some simple java code for creating and then accessing a 2D data set with a variable number of rows?

Currently, my prototype looks like:

ArrayList<Double> PeakList = new ArrayList<Double>();
Vector<Rectangle> peakVector = new Vector<Rectangle>();
Vector<Double> keyVector = new Vector<Double>();

if(PeakList.contains((double)i+newStartingPoint)){
    Rectangle myRect = new Rectangle(x2-5, y2-5, 10, 10);
    boolean rectFound = peakVector.contains(myRect);
    System.out.println("rectFound is:  "+rectFound);
              Double myPeak = ((double)i+newStartingPoint);
    if(rectFound!=true){
        peakVector.add(myRect);
                       keyVector.add(myPeak);
        System.out.println("rectFound was added.");
    }else{System.out.println("rectFound was NOT added.");}
}

I then enumerate through the data for subsequent processing with something like the following:

Enumeration e = peakVector.elements();
    while (e.hasMoreElements()) {
        g2.fillRect(peakVector.lastElement().x, peakVector.lastElement().y, 10, 10);
    }

As you can see, there is no way to subsequently integrate the keys with the rectangles. That is why I am looking for a 2D object to use. Can anyone show me how to fix this code so that I can associate keys with rectangles and subsequently access the appropriately associated data?


Solution

  • Why not simply use a HashMap<Double, Rectangle>?

    Edit: no, there are significant problems with this since there's no guarantee that two doubles will equal each other even though numerically they should. Does it have to be Double? Could use use some other numeric or String representation such as a Long? Is there a physical reality that you're trying to model?