[英]Cannot access object variable from class method(Java)
A homework assignment requires me to make a bag data structure in Java by implementing java.util.Collections. 一项家庭作业需要我通过实现java.util.Collections在Java中创建bag数据结构。 The bag data must be stored in an array.
行李数据必须存储在数组中。 I cannot seem to be able to get my class methods to access the array I give each object in the class.
我似乎无法使我的类方法访问我为类中的每个对象提供的数组。
Here's the code giving me the issue: 这是给我问题的代码:
import java.util.*;
import java.lang.*;
class Bag<T> implements Collection<T> {
//MAIN METHOD///////////////////////////////
public static void main(String[] args) {
Bag<Integer> bravo = new Bag<Integer>();
System.out.println(bravo.size());
}///////////////////////////////////////////
//CONSTUCTOR///////////////////////////
public Bag() {
T[] bagarray = (T[])new Object[10];
}
///////////////////////////////////////
//METHODS/////////////////////////////////////////////////////////////////////////////////
public int size() {
int temp;
temp = bagarray.length;
return temp;
}
During compile I'm given an cannotfindsymbol error for bagarray. 在编译期间,我收到了bagarray的cannotfindsymbol错误。 Yet, I have written code before performing this exact same maneuver.
但是,在执行完全相同的操作之前,我已经编写了代码。
It has to be some minute detail, but I've been racking my brain for a while on this problem. 它必须是一些细节,但是我已经花了一段时间来解决这个问题。 Where am I going wrong?
我要去哪里错了?
The array should be an instance variable; 该数组应该是一个实例变量; it is currently a local in the constructor.
当前是构造函数中的本地对象。
Local variable declaration: 局部变量声明:
//CONSTUCTOR///////////////////////////
public Bag() {
T[] bagarray = (T[])new Object[10];
}
Member variable declaration: 成员变量声明:
T[] bagarray;
//CONSTUCTOR///////////////////////////
public Bag() {
bagarray = (T[])new Object[10];
}
You want the latter of the two. 您需要两者中的后者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.