0
我已經完成了多次該代碼,但似乎無法理解它的行爲。當從ArrayList <Area>以外的區域訪問區域的邊界時,收到的矩形不正確
我在添加許多Area
實例到ArrayList
for循環,同時也產生另一個Area
這是所有那些添加到陣列(然而這汞齊化Area
從不加入到ArrayList
)的合併。
當試圖從另一個類中檢索ArrayList
的第一項時,它會給我合併的Area
的邊界,它從來沒有添加過!?!?!
import java.awt.Shape;
import java.awt.geom.Area;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
public class CorruptArray {
public ArrayList<Area> arrayList = new ArrayList<Area>();
public CorruptArray(){
double x = 100.0;
double y = 200.0;
double width = 100.0;
double height = 200.0;
Area map = null;
int i = 5;
for(int j =0 ; j<i; j++){
arrayList.add(new Area(new Rectangle2D.Double(x,y,width,height)));
x+=10;
y+=10;
width+=10;
height+=10;
}
int k = 0;
for(Area area : arrayList){
System.out.println("INITIAL BOUNDS ON ENTRY: " + area.getBounds().toString());
if(k == 0){
map = area;
k++;
}else{
map.add(area);
}
System.out.println("OVERALL JOINED AREA - map " + map.getBounds().toString() + "\n");
}
TestArray test = new TestArray(this);
}
private static class TestArray{
TestArray(CorruptArray ca){
System.out.println("\n\n");
for(Area area : ca.arrayList){
System.out.println("RETRIVAL OF BOUNDS FROM TestArray: " + area.getBounds().toString());
}
}
}
public static void main(String args[]){
new CorruptArray();
}
運行程序時,這是輸出I得到:
INITIAL BOUNDS ON ENTRY: java.awt.Rectangle[x=100,y=200,width=100,height=200]
OVERALL JOINED AREA - map java.awt.Rectangle[x=100,y=200,width=100,height=200]
INITIAL BOUNDS ON ENTRY: java.awt.Rectangle[x=110,y=210,width=110,height=210]
OVERALL JOINED AREA - map java.awt.Rectangle[x=100,y=200,width=120,height=220]
INITIAL BOUNDS ON ENTRY: java.awt.Rectangle[x=120,y=220,width=120,height=220]
OVERALL JOINED AREA - map java.awt.Rectangle[x=100,y=200,width=140,height=240]
INITIAL BOUNDS ON ENTRY: java.awt.Rectangle[x=130,y=230,width=130,height=230]
OVERALL JOINED AREA - map java.awt.Rectangle[x=100,y=200,width=160,height=260]
INITIAL BOUNDS ON ENTRY: java.awt.Rectangle[x=140,y=240,width=140,height=240]
OVERALL JOINED AREA - map java.awt.Rectangle[x=100,y=200,width=180,height=280]
RETRIVAL OF BOUNDS FROM TestArray: java.awt.Rectangle[x=100,y=200,width=180,height=280]
RETRIVAL OF BOUNDS FROM TestArray: java.awt.Rectangle[x=110,y=210,width=110,height=210]
RETRIVAL OF BOUNDS FROM TestArray: java.awt.Rectangle[x=120,y=220,width=120,height=220]
RETRIVAL OF BOUNDS FROM TestArray: java.awt.Rectangle[x=130,y=230,width=130,height=230]
RETRIVAL OF BOUNDS FROM TestArray: java.awt.Rectangle[x=140,y=240,width=140,height=240]
我認爲只會是一個問題,如果我說'面積= map'and即使這樣,爲什麼要我的後續調整如果我已經移動到列表中的其他項目,映射'ArrayList'中的第一個區域? –
您已將第一個「區域」對象的*引用*複製到了「映射」變量。一個'Area'實例現在被'map'引用,並且列表中的第一個條目('arraylist.get(0)')和'map.getBounds()'和'arraylist.getBounds()'獲得邊界來自同一地區。 –
感謝清除那:) –