gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
java Struct深拷贝
- User
java Struct深拷贝
- Assistant
Java并没有标准的Struct类,可能指的是自定义的结构体类。
在Java中,对象的拷贝分为浅拷贝和深拷贝,浅拷贝只复制对象的引用,深拷贝则会创建一个新的对象并复制所有属性。
要实现深拷贝需要实现Serializable接口,并使用对象的序列化和反序列化方法来完成。
以下是一个自定义的Person类的深拷贝示例:
import java.io.*; class Person implements Serializable { String name; int age; Address address; Person(String name, int age, Address address) { this.name = name; this.age = age; this.address = address; } public Person deepCopy() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return (Person)ois.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); return null; } } } class Address implements Serializable { String country; String city; Address(String country, String city) { this.country = country; this.city = city; } } public class DeepCopyDemo { public static void main(String[] args) { Address address = new Address("China", "Beijing"); Person person1 = new Person("张三", 20, address); Person person2 = person1.deepCopy(); System.out.println(person1 == person2); // false,说明是不同的对象 System.out.println(person1.address == person2.address); // false,说明地址也是不同的对象 } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.