[英]how to access an array within an object
Write a fully-documented class named Menu which stores a list of items in an array and provides an interface to interact with this list. 编写一个文档齐全的类,名为Menu,该类将项目列表存储在数组中,并提供与该列表进行交互的接口。 A Menu can hold up to 50 items at a time, so use the final variable MAX_ITEMS = 50.
菜单一次最多可以容纳50个项目,因此请使用最终变量MAX_ITEMS = 50。
I created the constructor and a separate class called MenuItem 我创建了构造函数和一个名为MenuItem的单独类
public class Menu implements Cloneable {
final int MAX_ITEMS = 50;
public Menu(){
MenuItem[] menu = new MenuItem[MAX_ITEMS];
}
}
I want to create a method that clones a Menu. 我想创建一个克隆Menu的方法。 How do I access the properties of each individual MenuItem within Menu?
如何访问菜单中每个菜单项的属性?
I don't think you have to go through all that, assuming A is the menu... 我认为您不必经历所有这些,假设菜单是A ...
public static Menu clone(){
Menu B = this;
return B;
}
Then simply call it using 然后只需使用
Menu B = A.clone();
You're creating MenuItem[] menu
as a local variable and never storing it after the constructor. 您正在将
MenuItem[] menu
创建为局部变量,并且永远不会将其存储在构造函数之后。 So not only can you not clone it, you can't ever access it again. 因此,您不仅无法克隆它,而且再也无法访问它。
Try using a field for the menu
variable, like this: 尝试对
menu
变量使用字段,如下所示:
public class Menu implements Cloneable {
final int MAX_ITEMS = 50;
private MenuItem[] menu;
public Menu(){
menu = new MenuItem[MAX_ITEMS];
}
}
Now any method within the Menu class can access the menu
you set during construction. 现在,Menu类中的任何方法都可以访问您在构造期间设置的
menu
。
As for cloning, it depends how deeply you want to clone. 至于克隆,这取决于您要克隆的深度。 If you just want a new Menu object that refers to the same
menu
array in memory, see cloneOne. 如果只希望一个新的Menu对象引用内存中的相同
menu
数组,请参见cloneOne。 If you want a new Menu object with a new menu
array containing the same objects as the old menu
array, see cloneTwo. 如果要使用包含与旧
menu
数组相同的对象的新menu
数组的新Menu对象,请参见cloneTwo。 If you want to go further than that, you'll have to put up some details for the MenuItem class: 如果您想做得更多,则必须为MenuItem类提供一些详细信息:
public class Menu implements Cloneable {
final int MAX_ITEMS = 50;
private MenuItem[] menu;
public Menu(){
menu = new MenuItem[MAX_ITEMS];
}
public Menu cloneOne(){
Menu a = new Menu();
a.menu = menu;
return a;
}
public Menu cloneTwo(){
Menu a = new Menu();
a.menu = new MenuItem[menu.length];
for(int i = 0; i < menu.length; i++)
a.menu[i] = menu[i];
return a;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.