简体   繁体   English

JAVA clone()将对象复制到其他类对象

[英]JAVA clone() copy object to other class objects

I want to ask you how can i copy firstClass objects to secondClass objects? 我想问你如何将firstClass对象复制到secondClass对象?

Is this possible to figure it out by using clone()? 是否可以使用clone()弄清楚?

The situation looks like this: 情况看起来像这样:

I have a class fx firstClass. 我有一班fx firstClass。 And I need to clone firstClass objects to secondClass objects (and these cloned objects must be stored into array) 而且我需要将firstClass对象克隆为secondClass对象(并且这些克隆的对象必须存储到数组中)

Thanks 谢谢

EDITED: 编辑:

sorry for a little information. 抱歉,请提供一些信息。 But my task looks like this: 但是我的任务看起来像这样:

Write a Garage class whose objects can hold up to some number of Vehicle objects in an array. 编写一个Garage类,该对象的对象最多可以容纳一个数组中的Vehicle对象。 Make Garage a Cloneable type, and write a proper clone method for it. 将Garage设为可克隆类型,并为其编写适当的克隆方法。 Write a Garage.main method to test it. 编写Garage.main方法进行测试。

By convention, Object.clone() method and its overrides should always return an object of the original type. 按照约定, Object.clone()方法及其覆盖应该始终返回原始类型的对象。

x.clone().getClass() == x.getClass() x.clone()。getClass()== x.getClass()

So it should be impossible to create an object of different type if clone() is properly implemented and used. 因此,如果正确实现并使用clone()则不可能创建不同类型的对象。

It's not cloning. 这不是克隆。 If you have two unrelated classes, the best you can do is write a constructor for SecondClass that takes FirstClass object as an argument and writes all the values into the proper fields: 如果您有两个不相关的类,则最好的办法是为SecondClass编写一个构造函数,该构造函数将FirstClass对象作为参数并将所有值写入适当的字段中:

public SecondClass (FirstClass source){
  this.valueA = source.getValueA();
  this.valueB = source.getBValue();
  this.valueC = source.getProperCValue();
  ...
}

something like this?! 这样的东西?

class Foo{
  private String bar;
  public Object clone(){
    Foo f=new Foo();
    f.setBar(this.bar);
    //filling and copy the f attributes
    guys.add(f);
  }
   ///
   private final static List<Foo> guys=new ArrayList<>();
   ///
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM