2012-10-23 39 views
0

這將很難解釋,但我會盡我所能。Java ArrayList和對象問題。重置值

我有3個班和一個主班。這些課程是城市,旅遊和人口。一個人口有一個X數量的遊覽數組列表,遊覽中有一個X數量的城市數組列表。城市只是一個X和Y座標。 當我創建新的旅遊時,其中的城市是隨機的,然後我將旅遊添加到人口數列表中,並且工作正常,輸出是隨機的。但是,如果我再次輸出數組列表,他們不再隨機化,所有的巡視都是一樣的。 我認爲這將是更容易解釋通過展示一些代碼:

Population.java

public class Population { 

private ArrayList<Tour> toursList; 

public Population(int size, ArrayList<City> loadedCities) 
{ 
    toursList = new ArrayList<Tour>(); 

    // Fill the population with the number of tours 
    for (int i = 0; i < size; i++) { 
     Tour newTour = new Tour(loadedCities); 
     newTour.setId(i); 
     toursList.add(newTour); 
    } 

} 

public void output() 
{ 
    for (Tour tour : toursList) 
     System.out.println(tour.toString()); 
} 
} 

Tour.java

public class Tour { 

private ArrayList<City> tour; 
private int id = 0; 

public Tour(ArrayList<City> cities) 
{ 
    Collections.shuffle(cities); 
    tour = cities; 
} 

public void setId(int i) 
{ 
    this.id = i; 
    System.out.println("Constructor: "+toString()); 
} 

public int getId() 
{ 
    return id; 
} 

public String toString() 
{ 
    String str = "Tour: "+id+" - "; 
    for (City city : tour) { 
     str += city.toString()+" | "; 
    } 
    return str; 
} 
} 

City.java

public class City { 

private int code; 
private Double y; 
private Double x; 

public City(int code, Double y, Double x) 
{ 
    this.code = code; 
    this.y = y; 
    this.x = x; 
} 

public int getCode() 
{ 
    return code; 
} 

public Double getX() 
{ 
    return x; 
} 

public Double getY() 
{ 
    return y; 
} 

public String toString() 
{ 
    return "Code: "+this.code+" - X: "+this.x+" Y: "+this.y; 
} 
} 

然後主類只是使這些加載後調用Ë城市的ArrayList:

Population population = new Population(10, cities); 
population.output(); 

控制檯輸出爲少數的println的如下(精簡版):

Constructor: Tour: 0 - Code: 2 - X: 42373.8889 Y: 11108.6111 
Constructor: Tour: 1 - Code: 28 - X: 43026.1111 Y: 11973.0556 
Tour: 0 - Code: 8 - X: 42983.3333 Y: 11416.6667 
Tour: 1 - Code: 8 - X: 42983.3333 Y: 11416.6667 

你可以看到旅行團現已全部變成相同的,以相同的順序。

請讓我知道你是否需要任何更多信息或需要我解釋清楚的問題。

很多謝謝。

+0

大小用於配置有多少遊覽,這將是一個接口上的選項,以增加遊覽的數量。 –

+0

啊,我明白了;我沒有注意。 –

回答

2

對所有遊覽使用相同ArrayList<City> cities

Tour構造函數應該是這樣的:

tour = new ArrayList<City>(cities); 
Collections.shuffle(tour); 
+0

當然。我知道這會很簡單,但我看不到它!謝謝!附:系統讓我在3分鐘內接受你的答案:) –

0

Java使用可變集合。既然你將同一個集合傳入所有的遊覽中,它會被洗牌很多次,但最終所有的遊覽都會引用相同的,混亂的集合。

兩件事情,從這個學習:

    如果你想修改你獲得通過在收集,請先複印一份(如 new ArrayList(collectionToCopy)
  1. 如果你通過你自己給別人的集合
  2. ,首先確保他不能更改它(例如Collections.unmodifiableList(myCollection)

在Java職業生涯中,您將很多次都陷入這個陷阱。如果你不這樣做,別人會爲你做。