【问题标题】:Changing static reference from a non static field?从非静态字段更改静态引用?
【发布时间】:2012-12-04 06:04:55
【问题描述】:

我有一个私有 int 数组,我需要以某种方式找到长度,但我不能在静态类下做到这一点。我必须保持类静态,是否可以添加另一种方法来将 a.length 更改为其他内容?

问题是由 a.length 引起的。

private int [] a;

public static IntegerSet union(IntegerSet otherSet, IntegerSet nextSet) {

                for(int i=0; i<a.length; i++) {
                  if (otherSet.isSet(i))
                    nextSet.insertElement(i);
                }

                return nextSet;
              }

【问题讨论】:

    标签: java string-length


    【解决方案1】:

    正如我所说的使用

    public int lenghtOfArray(){
          return this.a.lenght;
    }
    

    并将您的方法更改为

    public static IntegerSet union(IntegerSet otherSet, IntegerSet nextSet) {
          for(int i=0; i<otherSet.length(); i++) {
               if (otherSet.isSet(i))
                    nextSet.insertElement(i);
               }
               return nextSet;
          }
    

    【讨论】:

      【解决方案2】:

      要么将a 设为静态,要么将您的类的实例作为参数传递给union 方法并访问该实例的a 字段。

      【讨论】:

        【解决方案3】:

        你需要引用一个对象的字段:

        private int [] a;
        
        public static IntegerSet union(IntegerSet otherSet, IntegerSet nextSet) {
            . . .
            for(int i=0; i<otherSet.a.length; i++) {
                . . .
            }
        }
        

        【讨论】:

          【解决方案4】:

          你不是在静态类中引用a.length;你是从一个静态的方法做的。静态方法永远不能引用非静态成员变量。

          看起来好像你有一个错误。你为什么要反对a.length?您应该询问otherSetnextSeta 成员。

          【讨论】:

            猜你喜欢
            • 2023-03-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-11-04
            • 2014-02-02
            • 1970-01-01
            相关资源
            最近更新 更多