简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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