class Point
{
int x;
int y;
Point(int x,int y)
{
this.x = x;
this.y = y;
}
}Point [] src = new Point[] {new Point(1,1),new Point(2,2)};Point [] dest = new Point[2];System.arraycopy(src,0,dest,0.src.length);///这样出来的两个数组会指向同一块内存,修改一个,另一个也会变//如何实现这两个数组独立?
{
int x;
int y;
Point(int x,int y)
{
this.x = x;
this.y = y;
}
}Point [] src = new Point[] {new Point(1,1),new Point(2,2)};Point [] dest = new Point[2];System.arraycopy(src,0,dest,0.src.length);///这样出来的两个数组会指向同一块内存,修改一个,另一个也会变//如何实现这两个数组独立?
{
public static void main(String[] args)
{
Point p1 = new Point(1,1);
Point p2 = new Point(2,2);
Point [] src = new Point[] {p1, p2}; Point [] dest = new Point[]{(Point)p1.clone(), (Point)p2.clone()}; dest[1].setX(5);
System.out.println(src[1].getX()+ " " + dest[1].getX()); }
}
class Point implements Cloneable
{
int x;
int y; Point(int x, int y)
{
this.x = x;
this.y = y;
}
public Object clone()
{
Object o = null;
try
{
o = (Point)super.clone();
}
catch(CloneNotSupportedException e)
{
System.out.println(e.toString());
}
return o;
}
public int getX()
{
return x;
}
public void setX(int x)
{
this.x = x;
}
public int getY()
{
return y;
}
public void setY(int y)
{
this.y = y;
}
}
import java.util.Arrays;public class examples
{
public static void main(String[] args)
{
int[] src = new int[] {1, 1};
int[] dest = new int[2];
System.arraycopy(src, 0, dest, 0, src.length);
System.out.println("Original: ");
for (int i = 0; i < src.length; i++)
System.out.println(src[i]);
for (int i = 0; i < dest.length; i++)
System.out.println(dest[i]);
System.out.println("Modified: ");
dest[1] = 2;
for (int i = 0; i < src.length; i++)
System.out.println(src[i]);
for (int i = 0; i < dest.length; i++)
System.out.println(dest[i]);
}
}
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.io.Serializable;public class Test
{ public static void main(String[] args) throws OptionalDataException,
IOException, ClassNotFoundException
{
Point p1 = new Point(1, 1); Point p2 = new Point(2, 2); Point[] src = new Point[] { p1, p2 }; Point[] dest = new Point[] { (Point) src[0].deepClone(),
(Point) src[1].deepClone() }; dest[1].setX(5); System.out.println(src[1].getX() + " " + dest[1].getX()); }}class Point implements Serializable
{
int x;
int y; Point(int x, int y)
{
this.x = x;
this.y = y;
} public Object deepClone() throws IOException, OptionalDataException,
ClassNotFoundException
{
ByteArrayOutputStream baus = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baus); oos.writeObject(this); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baus.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); ois.close(); return ois.readObject(); } public int getX()
{
return x;
} public void setX(int x)
{
this.x = x;
}}这是用序列化的方式,其实大同小异,两种都经过了测试
哦,明白了,我copy的是数值,lz需要的是Point类对象的引用,谢谢
dest都成NULL,不知道为什么