Java 如何阻止方法更新其外部的数组
希望得到一些帮助-我被要求使用uni的方法编写一个酒店房间系统。在我尝试按字母顺序排列数组之前,一切都进行得很顺利 我已经设法让它在方法内订购,但它更新了主阵列(hotel)。我想让它保持在order方法中,如果这有意义的话 我在下面加入了一个没有所有功能的精简版本 目前,它将对阵列酒店进行重新排序,因此如果您查看房间,阵列将打印“e、e、e等,乔治、彼得、罗伯特”,而不是保留其原始形式“e、罗伯特、彼得、e、e等,乔治”Java 如何阻止方法更新其外部的数组,java,methods,Java,Methods,希望得到一些帮助-我被要求使用uni的方法编写一个酒店房间系统。在我尝试按字母顺序排列数组之前,一切都进行得很顺利 我已经设法让它在方法内订购,但它更新了主阵列(hotel)。我想让它保持在order方法中,如果这有意义的话 我在下面加入了一个没有所有功能的精简版本 目前,它将对阵列酒店进行重新排序,因此如果您查看房间,阵列将打印“e、e、e等,乔治、彼得、罗伯特”,而不是保留其原始形式“e、罗伯特、彼得、e、e等,乔治” public static void main(String[] arg
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String roomName;
int roomNum = 0;
String[] hotelRef = new String[12];
String[] hotel = new String[12];
initialise(hotel); //initialise
while (roomNum < 13) {
System.out.println("Please select from the menu:");
System.out.println("V : View rooms");
System.out.println("O : Order Guests alphabetically");
String selection = input.next();
switch (selection) {
//There are more switch cases on the original version
case "O":
order(hotel);
break;
default:
System.out.println("");
}
}
}
private static void order(String[] hotelRef) {
int j;
boolean flag = true; //will determine when the sort is finished
String temp;
String[] order = new String[12];
order = hotelRef;
while (flag) {
flag = false;
for (j = 0; j < order.length - 1; j++) {
if (order[j].compareToIgnoreCase(order[j + 1]) > 0) {
//ascending sort
temp = order[j];
order[j] = order[j + 1]; // swapping
order[j + 1] = temp;
flag = true;
}
}
}
for (int y = 0; y < order.length; y++) {
if (!order[y].equals("e")) {
System.out.println("Room " + y + " is occupied by " + order[y]);
}
}
System.out.println("Ordering completed");
}
publicstaticvoidmain(字符串[]args){
扫描仪输入=新扫描仪(System.in);
字符串roomName;
int roomNum=0;
字符串[]hotelRef=新字符串[12];
字符串[]酒店=新字符串[12];
初始化(酒店);//初始化
while(roomNum<13){
System.out.println(“请从菜单中选择:”);
System.out.println(“V:视图室”);
System.out.println(“O:按字母顺序排列客人”);
字符串选择=input.next();
开关(选择){
//原始版本上有更多的开关盒
案例“O”:
订单(酒店);
打破
违约:
System.out.println(“”);
}
}
}
私有静态无效订单(字符串[]hotelRef){
int j;
boolean flag=true;//将确定排序何时完成
字符串温度;
字符串[]顺序=新字符串[12];
订单=hotelRef;
while(旗帜){
flag=false;
对于(j=0;j0{
//升序排序
温度=订单[j];
顺序[j]=顺序[j+1];//交换
订单[j+1]=温度;
flag=true;
}
}
}
对于(int y=0;y
您应该克隆hotelRef
而不是像这样分配引用order=hotelRef代码>
创建订单数组时,可以执行以下操作:
String[] order = new String[hotelRef.length]; // to make sure that order has the right size.
而不是order=hotelRef代码>
for (int i=0;i<order.length;i++)
order[i]=hotelRef[i]; // thereby cloning
对于(int i=0;i您可以使用订购方法复制酒店阵列:
String[] hotelCopy = new String[hotelRef.length];
System.arraycopy(hotelRef, 0, hotelCopy, 0, hotelRef.length);
然后在您的订购方法中使用hotelCopy。问题在于以下几行
订单=hotelRef
换成
order=hotelRef.clone()
虽然您正在创建一个新对象,但您仅将引用指定给外部对象。因此,无论您在内部对象中所做的任何更改都将反映到外部对象。order=hotelRef
这里您无意中(而不是克隆阵列)“刚下订单”还指向hotelRef中的值,所有更改也将反映在hotelRef中。如果不想对原始数组进行更改,请不要使用原始数组。创建数组的副本,这样您就有机会过滤其内容并避免显示空房间。。。