gpt4 book ai didi

java - 从数组到数组创建新对象

转载 作者:行者123 更新时间:2023-12-02 05:47:25 25 4
gpt4 key购买 nike

我正在尝试从所有可能对象的数组到另一个数组生成新的唯一对象。我的想法是,我有 3 个实现 Region 类的类,并且它们有自己的方法。这3个类在我的ArrayList<Region> arr中。我随机选择一个类并将其添加到 ArrayList<Region> ALL_REGIONS在 for 循环中。问题是从 arr 添加的对象不是唯一的,它们是相同的。从他们的名字就可以看出这一点。每个区域都必须有其唯一的名称和其他设置,但它们没有。这是我到目前为止的代码:

public void generateRegions(){
ArrayList<Region> arr = Regions.getAllRegions();
Random rnd = new Random();
String ntype;
int regcounter = 5;
int b;

for(int i = 0; i < regcounter; i++){
ALL_REGIONS.add(arr.get(rnd.nextInt(arr.size())));
ntype = "n" + ALL_REGIONS.get(i).getType();

b = rnd.nextInt(Regions.getNtypeSize(ntype));
UI.print("b: " + b);
ALL_REGIONS.get(i).setName(Regions.getArrayName(ntype, b));
}
}

public static ArrayList<Region> getAllRegions(){
ArrayList<Region> arr = new ArrayList<Region>();

arr.add(new Highlands());
arr.add(new Cave());
arr.add(new Oasis());

return arr;
}

getArrayName从数组返回区域的字符串名称和 getNtypeSize返回一个int,数组的大小String[]其中包含所有现在并不重要的名称。

那么..我怎样才能让每个洞穴、每个绿洲都是独一无二的/作为一个单独的对象?

**编辑:**请求的 getArrayName() 和 getNtypeSize() 方法如下:

public static String getArrayName(String ntype, int t) {
String ans = null;

if(ntype.equals("ncave")){
if(t<=ncaveSize)
ans = ncave[t];
}else if(ntype.equals("noasis")){
if(t<=noasisSize)
ans = noasis[t];
}else if(ntype.equals("nhighlands")){
if(t<=noasisSize)
ans = nhighlands[t];
}

//Can happen when t is bigger then ntype size or
// if ntype string is wrong
if(ans == null){
UI.printerr("getArrayNames: ans is empty/null");
}
UI.printerr(ans);
return ans;
}

public static int getNtypeSize(String ntype){
int ans = 0;

if(ntype.equals("ncave")){
ans = ncaveSize;
}else if(ntype.equals("noasis")){
ans = noasisSize;
}else if(ntype.equals("nhighlands")){
ans = nhighlandsSize;
}else
UI.printerr("getNtypeSize: returned 0 as an error");

return ans;
}

最佳答案

问题出在这一行:

ALL_REGIONS.add(arr.get(rnd.nextInt(arr.size())));

此处,您并不是向 ALL_REGIONS 添加对象。相反,每次您向“arr”中的对象添加引用时。

例如,每次 rnd.nextInt(arr.size()) 返回 2 时,您需要将对 arr[2] 的引用添加到 ALL_REGIONS 。因此,实际上,ALL_REGIONS 中的每个条目都引用 arr 中的对象之一。 (在此特定示例中,是您在 getAllRegions() 中添加的 3 个对象之一)

实际上,这意味着 ALL_REGIONS 中的每个 Highlands 对象引用都指向同一个对象 => arr[0]同样,ALL_REGIONS 中的每个 Cave 引用都指向 arr[1],每个 Oasis 引用都指向 arr[2]

沿着这条线应该可以解决问题:

Region reg = arr.get(rnd.nextInt(arr.size()))  
ALL_REGIONS.add(reg.clone()); // this is just meant to be a sort of pseudo-code. Use a clone() method to create a new copy of the object and that copy to ALL_REGIONS.

关于java - 从数组到数组创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23919803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com