简体   繁体   English

将对象数组传递给java中的方法

[英]Passing an array of objects to a method in java

Hello guys I have a question.大家好,我有一个问题。 I have an error when I am trying to pass an array of object to a method My class当我尝试将对象数组传递给方法时出现错误 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
   }

So sorry for the long post ...很抱歉这篇很长的帖子......

findMaxPos is a static method of your class staticMethod. findMaxPos 是您的类 staticMethod 的静态方法。

When you are not calling a static function inside the class where it is defined, you need to call it with the name of the class before:当您不在定义它的类中调用静态函数时,您需要使用之前的类名调用它:

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.
}

Note that in java, the convention is to give classes a name which begin with an uppercase letter (Names which begin with a lowercase letters are given to instances).请注意,在 java 中,约定是给类一个以大写字母开头的名称(以小写字母开头的名称是给实例的)。

Well, the above solution should work but apart from that, there are a couple of other things that need to be taken into consideration.好吧,上述解决方案应该可行,但除此之外,还有一些其他事项需要考虑。

  1. public Object(int a,) Constructor is incomplete. public Object(int a,) 构造函数不完整。
  2. semicolon(;) is missing in max = name[0], pos = 0 max = name[0], pos = 0 中缺少分号(;)
  3. Most importantly the return type of max and Pos is undefined.最重要的是 max 和 Pos 的返回类型是未定义的。 POs can be int but the variable max should be of the type Object. PO 可以是 int 但变量 max 应该是 Object 类型。
  4. If the return type of max is object you can't use (name[i] >max ) as it is undefined for object type.如果 max 的返回类型是 object,则不能使用 (name[i] >max ),因为它未针对对象类型定义。 Rectify these mistakes hopefully your code will run fine.纠正这些错误,希望您的代码能够正常运行。

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

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