code:class atom{
 int i;
 int j;
 void atom(int i, int j){
   this.i =i;
   this.j = j;
 }
}class list{
  atom [] element;
  String name;
  
  viod list(atom[] element, String name){
     this.element = element;
     this.name = name;
  } 
}
public class Main{
 public static void main(String args[]){
  atom [] tmp;
  tmp[0] = new atom(1,2);
  tmp[1] = new atom(2,3);
  list ls = new list(tmp, "haha");
 
 }
}这样对么?好像数组拷贝有问题.
还有一个问题是:main() 是static的,所以要求在main()里面调用的函数也要是static的,搞得程序运行很慢,有什么变通的方法??

解决方案 »

  1.   

    你的数组没有拷贝,只是传递了一个引用
    public atom(atom a) {
      atom at=new atom(a.i,a.j);
    }len=element.length;
    this.element=new atom[len];
    for(int i=0;i<len;i++) {
      this.element[i]=new atom(element[i]);
    }
      

  2.   

    要在main()里面调用非static的函数,只能创建一个对象,用这个对象来调用函数
      

  3.   

    数组拷贝用System.arrayCopy(src,src_pos,dest,dest_pos,length);
      

  4.   

    第一:楼主的程序能运行吗,new atom(1,2),你的类atom根本就没有对应的构造函数,只有一个成员方法void atom(int i, int j)第二:静态方法main调用静态方法,很正常的啊,怎么会至于让你的程序运行很慢呢第三:拜托一开始写程序就要求自己按照程序规范来写,让你的类名大写字母开始,尽量避免使用易混肴的类名,如list我现在项目组就有一个所谓的高程,写出来的代码我都不想看,代码表现很不规范,算法也没见着过人之处,说实话让我考二级,我还未必能过
    考级与实际项目完全是两回事,项目中不允许写很多考试中出现的的代码,比如x++x++++x什么,写给谁来读呢,想知道它怎么执行,用反编译(或反汇编)看看就知道了
      

  5.   

    改进的程序为
    class Atom {
        int i;
        int j;    Atom(int i, int j) { //去掉void,声明为一个构造函数
            this.i = i;
            this.j = j;
        }
    }class UrList {
      
        Atom[] element;
        String name;    UrList(Atom[] element, String name) { //去掉void,声明为一个构造函数
            this.element = element;
            this.name = name;
        }
    }public class Main {
        public static void main(String[] args) {
            Atom[] tmp = new Atom[2]; //需要初始化后才能引用
            tmp[0] = new Atom(1, 2);
            tmp[1] = new Atom(2, 3);
            UrList ls = new UrList(tmp, "haha");
            System.out.println(ls);
        }
    }
      

  6.   

    问题基本解决,准备加分,不过还有个疑问:如果atom改为
    class atom{
     int i;
     String j; public atom(int i, String j){
       this.i =i;
       this.j = j;
     }
    }String 是对象,能直接用等于么?如果不,那用什么?
      

  7.   

    Java 没有 C++ 的拷贝构造函数, this.j = j; 并没有拷贝对象实例本身而只是拷贝一个引用。Java 的引用可能有时候要换成 句柄来讲 可能更好,因为它跟  C++ 的 引用又不完全一样。