简体   繁体   English

如何将数组返回到单独的类?

[英]How to return an array to separate class?

If I write out an array the long way in a seperate class such as 如果我在单独的类中写一个数组很长的路要走

public Student [] getArray(){
    Student [] studentArray = new Student[3];
    studentArray[0] = new Student (”Mel”);
    studentArray[1] = new Student (”Jared”);
    studentArray[2] = new Student (”Mikey”);
    return studentArray;
}

Will the return statement return all the names to my other class that I'm actually going to run, or just one? return语句会将所有名称返回给我实际要运行的其他类,还是仅返回一个?

Here, the return statement will return the entire array, which means that the caller can access all three of the Student objects. 在这里, return语句将返回整个数组,这意味着调用方可以访问所有三个Student对象。 For example: 例如:

Student[] arr = getArray();
System.out.println(arr[0]); // Prints out Mel student
System.out.println(arr[1]); // Prints out Jared student
System.out.println(arr[2]); // Prints out Mikey student

If you want to return just one Student , then your return type would be Student and you would have to specifically pick which one to return. 如果您只想返回一个Student ,那么您的返回类型将是Student ,您必须专门选择要返回的那个。 In Java, returning an array always returns the entire array, and you don't need to say that you're returning all of the contents with it. 在Java中,返回数组始终会返回整个数组,而无需说您将返回所有内容。

Hope this helps! 希望这可以帮助!

Of course all the names. 当然是所有名字。 It returns your array which contains all your created Students. 它返回包含所有已创建学生的数组
I guess youre new to programming. 我想您是编程新手。 So read this to know what are arrays and how to use them. 因此,请阅读本文以了解什么是数组以及如何使用它们。

This statement 这个说法

Student[] studentArray = new Student[3];

creates a new array , capable of holding three references to Student instances and assigns the reference to this array to the local variable studentArray 创建一个新数组 ,该数组能够容纳对Student实例的三个引用 ,并将对该数组的引用分配给局部变量 studentArray

return studentArray;

returns the reference to this array to the caller of the method. 将对此数组的引用返回给方法的调用者。 He can use this array reference to get the references of the Student objects. 他可以使用此数组引用来获取Student对象的引用。

He can either store it in another variable or use it directly: 他可以将其存储在另一个变量中,也可以直接使用它:

Student[] callersArray = getArray();
System.out.println(callersArray[0]);  // will print a Student "Mel"

System.out.println(getArray()[0]);    // will print another(!) Student "Mel"

All values of the array are returned. 返回数组的所有值。 You can write it shorter: 您可以将其写得更短:

public Student [] getArray(){
  return new Student[]{new Student (”Mel”), new Student (”Jared”), new Student (”Jared”)};
}

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

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