【发布时间】:2024-01-01 19:28:01
【问题描述】:
package primary;
public class Room implements Cloneable{
int room_no;
private int leftStrength; //number of students sitting on left side
private int rightStrength;//number of students sitting on right side
private int capacity;
private int timeSlot;
private boolean checkBig;
boolean invigilanceRequired;
private int rightCapacity;
private int leftCapacity;
public Room(int room_no,int capacity)
{
this.room_no=room_no;
this.capacity=capacity;
rightStrength=0;
leftStrength=0;
timeSlot=0;
checkBig=true;
invigilanceRequired=true;
rightCapacity=capacity;
leftCapacity=capacity;
}
public Room(Room other)
{
this.room_no=other.room_no;
this.capacity=other.capacity;
this.rightStrength=other.rightStrength;
this.leftStrength=other.leftStrength;
this.timeSlot=other.timeSlot;
this.checkBig=other.checkBig;
this.invigilanceRequired=other.invigilanceRequired;
this.rightCapacity=other.rightCapacity;
this.leftCapacity=other.leftCapacity;
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}
我已经尝试过复制构造函数和 clone() 来制作 Room 对象的副本,但每次它给出相同的对象并且不复制。我发现它总是调用参数化的构造函数。 我调用 Room 复制构造函数的一小部分代码:
public TimeInterval(TimeInterval other) throws CloneNotSupportedException
{
course_to_room=new ArrayList<>();
map=new HashMap<>();
rooms=new ArrayList<>();
this.day_no=other.day_no;
this.time_interval=other.time_interval;
for(Course course:other.course_to_room)
{
this.course_to_room.add((Course)course.clone());
}
for(Room room:other.rooms)
{
Room tempRoom=new Room(room);
this.rooms.add(tempRoom);
}
for(Integer key:other.map.keySet())
{
ArrayList<Course> temp=other.map.get(key);
ArrayList<Course> newClone=new ArrayList<>();
for(Course course:temp)
{
newClone.add(new Course(course));
}
this.map.put(key, newClone);
}
}
在这里,我正在做精确的代码来复制 Room 对象:
TimeInterval save1=new TimeInterval(time1);
当我从以上 2 个对象(save1 和 time1)打印任何变量时,它们是不同的。
我正在添加输入命令和输出
System.out.println("Old time 1,Room 5 capacity left "+save1.R4.getRightCapacity());
System.out.println("Old time 2,Room 5 capacity left "+save2.R4.getRightCapacity());
System.out.println("Old time 2,Room 5 right strength "+save2.R4.getRightStrength());
System.out.println("Old time 1,Room 5 capacity left "+time1.R4.getRightCapacity());
System.out.println("Old time 2,Room 5 capacity left "+time2.R4.getRightCapacity());
System.out.println("Old time 2,Room 5 time 1 right strength "+time1.R4.getRightStrength());
输出:
旧时1号,5号房还剩60人
旧时2,5号房还剩60人
旧时2,房间5右力0
旧时 1,房间 5 剩余容量 0
旧时2,5号房还剩60人
旧时2,房间5时1右力60
【问题讨论】:
-
您能否更清楚地说明问题是什么,以及您是如何断定存在问题的?
-
我已经从 save1 和 time1 打印了 rightStrength 变量。 save1 显示 0。time1 显示 60。它处于循环状态,因此 time1 随时间变化,save1 应将此更改的值复制到 rightStrength。但是 rightStrength 仍然是 0。所以,我断定它正在调用参数化构造函数。
-
如果
TimeInterval上有一个rightStrength变量,你还没有显示它。请发帖minimal reproducible example。 -
向 cmets 添加代码格式不正确,请尝试编辑您的问题。 (如果您还提供您使用的打印语句以及您获得的结果和您期望的结果,这将有所帮助。准确有助于 *。)
-
您的问题与默认构造函数无关。
标签: java constructor copy clone