我試圖創建一個停車場程序,模擬何時將汽車添加到停車場。UnsupportedOperationException將類添加到集合
我的想法是創建一個類型的汽車列表,將汽車添加到固定容量列表(15)。
一切工作正常,直到我突然開始收到以下異常:
異常線程「main」 java.lang.UnsupportedOperationException
林很困惑,爲什麼這是現在發生因爲我沒有改變任何東西,異常似乎來來去去。
我使用netbeans,在此之前,我在源包中沒有識別出主類。
我可以列出的代碼下面爲您:
停車場類
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class CarPark
{
List<Car> spaces = Arrays.asList(new Car[15]); //Set max size of list to be 15
Scanner scanner = new Scanner(System.in);
public void initialise()
{
CarSize carSize = null;
CarValue carValue = null;
System.out.println("Please enter the registration Number");
String regNo = scanner.nextLine();
System.out.println("\nNow the size of the car");
System.out.println("0 - Small");
System.out.println("1 - Medium");
System.out.println("2 - Large");
int size = scanner.nextInt();
switch(size)
{
case 0: carSize = CarSize.Small; break;
case 1: carSize = CarSize.Medium; break;
case 2: carSize = CarSize.Large; break;
}
System.out.println("\nFinally the value of the car");
System.out.println("0 - Loq");
System.out.println("1 - Medium");
System.out.println("2 - High");
int value = scanner.nextInt();
switch(value)
{
case 0: carValue = CarValue.Low; break;
case 1: carValue = CarValue.Medium; break;
case 2: carValue = CarValue.High; break;
}
addCar(regNo, carSize, carValue);
showTotalCars();
}
//Adds the car to the list
public void addCar(String regNum, CarSize size, CarValue value )
{
Car car = new Car(regNum, size, value);
spaces.add(car);
}
public void showTotalCars()
{
System.out.println("Total Cars = " + spaces.size());
}
}
汽車類
public class Car
{
String RegistrationNumber = "";
CarSize size = null;
CarValue value = null;
public Car(String regNo, CarSize sizeOfCar, CarValue valOfCar)
{
RegistrationNumber = regNo;
size = sizeOfCar;
value = valOfCar;
}
@Override
public String toString()
{
return "Registration Number = " + RegistrationNumber
+ "\nSize = " + size.name()
+ "\nValue = " + value.name();
}
}
CarSize(枚舉類)
public enum CarSize
{
Small(0, "For small cars"),
Medium(1, "For medium cars"),
Large(2, "For large cars");
private final int Id;
private final String description;
CarSize(int identifier, String descr)
{
this.Id = identifier;
this.description = descr;
}
public int getId()
{
return Id;
}
public String getDescription()
{
return description;
}
}
CarValue(枚舉類)
public enum CarValue
{
Low(0, "For low value cars"),
Medium(1, "For medium value cars"),
High(2, "For high value cars");
private final int Id;
private final String description;
CarValue(int identifier, String descr)
{
this.Id = identifier;
this.description = descr;
}
public int getId()
{
return Id;
}
public String getDescription()
{
return description;
}
}
而進行研究,如果是我目前的問題聯繫在一起包問題,如上面提到的可能是由於內存不足,我不知道我已閱讀?
由於提前
有沒有辦法來限制在這種情況下,ArrayList的容量以15?要求只允許15輛車被添加到列表中。謝謝 – 2014-11-23 19:14:25
@KyleT不,沒有辦法。你應該在要向你的List中添加元素的方法中手動執行此操作。 – 2014-11-23 19:14:58
非常好的答案,你啓發了我更多的話題!謝謝。 – 2014-11-23 19:17:05