【问题标题】:Calling ArrayList From Another Class [duplicate]从另一个类调用 ArrayList [重复]
【发布时间】:2015-02-16 19:07:13
【问题描述】:

我在调用另一个类的数组列表时遇到问题。我在其中定义了一个名为 IntBag 的类和一个 arraylist 包。在 main 方法中,我想编写一个程序,使我能够从另一个类中更改数组列表的长度。当我尝试时,出现“找不到符号”错误。你能帮忙吗?

import java.util.*;
public class IntBag 
{
   private static ArrayList<Integer> bag = new ArrayList<Integer>(); 
   private int maxNumber;

   public IntBag(ArrayList bag, int maxNumber) 
   {
       this.bag = bag;
       this.maxNumber = maxNumber;  
   }

   public static ArrayList getBag()
   {
       return bag;
   }

   public int sizeArray(ArrayList bag)
   {    
    return bag.size();
   }
}
public class test
{

    public static void main(String[] args) 
    {
        Scanner scan = new Scanner(System.in);
        int choice, size;
        IntBag.getBag();
        System.out.println("Enter the size of an array : ");
        size = scan.nextInt();
        bag = new ArrayList<Integer>(size); 
     }
}

【问题讨论】:

    标签: java class arraylist calling-convention


    【解决方案1】:

    IntBag 是一个非静态类,这意味着要使用它,您必须创建该类的新实例。为此,您需要执行以下操作:

    IntBag name_of_object = new IntBag();
    

    然后,要引用这个对象内部的包,你可以通过调用来访问它:

    name_of_object.getBag();
    

    要从备用类更改 ArraryList 的大小,您需要在 IntBag 类中包含一个 setter 方法:

    public void setBag(ArrayList<Integer> newList) {
        this.bag = newList;
    }
    

    然后,在您的替代课程中,您可以执行以下操作:

    IntBag bag = new IntBag(new ArrayList<Integer>(), 10);
    bag.setBag(new ArrayList<Integer>())
    

    您也可以为 maxnumber 变量创建一个类似的设置器:

    public void setMaxNumber(int max) {
        this.maxNumber = max;
    }
    

    但请注意,ArrayList 没有最大或最小大小。当您在其中添加或删除变量时,它们会扩大或缩小。

    将代码放在哪里?

    好好想想吧。在您的主类中,您已经在创建对象,例如 Scanner 和两个整数。您只需以相同的方式创建 IntBag 对象,无论您需要在哪里使用它。所以你的主要方法可能看起来像这样:

    public static void main(String[] args) 
    {
        Scanner scan = new Scanner(System.in);
        int choice, size;
    
        System.out.println("Enter the size of an array : ");
        size = scan.nextInt();
    
        ArrayList<Integer> bag = new ArrayList<Integer>(); // arrraylists do not have a size. They automatically expand or decrease
    
        IntBag intBag = new IntBag(bag, 30); // creates a new IntBag object 
     }
    

    【讨论】:

    • 我想要这个:当我输入一个输入(大小)时,程序将调整 IntBag 类中定义的 arraylist 包的大小。
    • 我找不到我应该把对象放在哪里。你能告诉我代码吗?
    • @harold_finch 查看我对答案所做的补充。如果这回答了您的问题,请使用箭头下方的复选框将其标记为正确。如果没有,请告诉我有什么问题或您的其他问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 2021-08-14
    • 2015-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多