![](/img/trans.png)
[英]Passing array of objects in java and saving the array of objects in the called method
[英]Passing an array of objects to a method in java
大家好,我有一個問題。 當我嘗試將對象數組傳遞給方法時出現錯誤 My class
public class Object {
private int x1;
public Object(int a ,){
this.x1=a;
}
public class staticMethods{
public static void findMaxPos(Object[] name){
max = name[0]
pos = 0
for( int i=1; i<name.length ; i++){
if ( name[i] >max ){
max = name[i];
pos = i;
}
}
}
public class Example{
public static void main(String[] args) {
Object[] yp = new Object2[3];
yp[0] = new Object(5);
yp[1] = new Object(6);
yp[2] = new Object(8);
findMaxPos(type)// i get an error of the method findMaxPos is undefined for the type Example
}
很抱歉這篇很長的帖子......
findMaxPos 是您的類 staticMethod 的靜態方法。
當您不在定義它的類中調用靜態函數時,您需要使用之前的類名調用它:
public static void main(String[] args) {
Object[] type = new Object2[3];
yp[0] = new Object(5);
yp[1] = new Object(6);
yp[2] = new Object(8);
staticMethods.findMaxPos(type);// This should be ok.
}
請注意,在 java 中,約定是給類一個以大寫字母開頭的名稱(以小寫字母開頭的名稱是給實例的)。
好吧,上述解決方案應該可行,但除此之外,還有一些其他事項需要考慮。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.