I'm trying to create an ArrayList of type Item in my Store class and then test it in another class called StoreTester. I keep getting the error: The method get() is undefined for the type Store. So Java thinks my tester object of type Store is not an ArrayList even though I tried to make it so.
My Store class constructor:
import java.util.ArrayList;
public class Store
{
private ArrayList<Item> blockbuster;
public Store(){
blockbuster = new ArrayList<Item>();
}
public void addItem(Item i){
blockbuster.add(i);
}
}
This is my StoreTester class:
import java.util.ArrayList;
public class StoreTester{
public static void main(String[] args){
Store videostore = new Store();
System.out.print(videostore.toString());
System.out.print(videostore.get(0));
}
}
For some reason videostore.toString() works fine and prints out the list of objects I've added to it. Here is the method toString I wrote in my Store class:
public String toString(){
String item = "Items in store: " + "\n";
for(int j = 0; j < blockbuster.size(); j++){
item = item + blockbuster.get(j).getTitle() + "\n";
}
return item;
}
but as soon as I try to get() a specific object at an index or even use videostore.size(), i get the: method undefined error. Hopefully it is just a syntax error or something simple I've overlooked. Any help is appreciated.
Yes, Store does not have a method get
It can be implemented in Store as
public Item get (int index) {
// check for null, then
return blockbuster.get(index);
}
Store has-a ArrayList it is not Store is-a ArrayList
As #ElliottFrisch also mentions, you will need to implement a size method as well
public int size () {
// check for null, then
return blockbuster.size();
}
Related
I was wondering how to reference an ArrayList a different method than it was declared in.
For example I am writing a program that allows me to create a playlist of songs, so in one method I have createAPlaylist and then another method I have shuffle().
In my playlist method I have created an ArrayList but I am having trouble using this arrayList in my shuffle method. There is some code below for context:
public static void createAPlaylist() {
try {
System.out.println("We have the following tracks:");
ArrayList<String> songs = new ArrayList<String>();
String firstSong = jukebox.allTracks.get(0).getTitle();
songs.add(firstSong);
for (int index = 0; index < count; index++) {
System.out.println(SPACES + (index + 1) + ". " + jukebox.allTracks.get(index).getTitle());
}
System.out.println("Select a track to add to the playlist: ");
int songNumber = input.nextInt();
String songSelected = songs.get(songNumber);
songs.add(songSelected);
input.nextLine();
} catch (Exception e) {
System.out.println("\nplease select a valid song number.");
}
}
This is what method parameters are for:
public static void createAPlaylist() {
ArrayList<String> songs = new ArrayList<>();
shuffle(songs);
}
public static void shuffle(ArrayList<String> songs) {
// Do stuff with your ArrayList here
}
You can the arraylist from the createAPlaylist method and pass that to shuffle method:
Like:
public static List<String> createAPlaylist() {
...
...
...
return songs;
}
/// and then in shuffle method receive that as parameter :
public static void shuffle(List<String> songs){
// access that songs list by
}
Or you could:
Instead of method variable declare that arraylist as class variable..
Like:
public class ClassName{
public static ArrayList<String> songs = new ArrayList<String>();
public static void createAPlaylist() {
...
...
...
// reset the songs.
songs = new ArrayList<String>();
...
}
/// and then in another method:
public static void suffle(){
// access that songs list by
List<String> createdSongs = ClassName.songs;
}
In Java, variables are only available within the context they are created - so if you create an ArrayList inside a method, you cannot access it outside of that method unless you store it in the method’s class, or you return the variable from the method it’s made it.
You can either declare the ArrayList outside of the method, as a class field, like so:
public class Foo {
private static ArrayList<String> arrayList = new ArrayList<String>();
public static void createAPlaylist() {
arrayList.add();
etc...
}
}
Or you could return the ArrayList from the method like so:
public class Foo {
public static void main(String[] args) {
ArrayList<String> arrayList = createAPlaylist();
}
public static ArrayList<String> createAPlaylist() {
ArrayList<String> songs = new ArrayList<String>();
// Your code here
// Note that you have to return the list from
// inside the catch block!
// I’d recommend creating the ‘songs’ ArrayList
// outside of the ‘try’ block, so that you can
// have a fallback if something fails in the ‘try’
return songs;
}
}
I don’t know if you intend to have this all static. I’d think it will work better as non static, but that’s a matter for another question, so I’ve left it as-is in the examples.
Sorry if this isn’t formatted perfectly - I’m on a mobile device and don’t have my IDE.
We have to create a object of any class to use their funtionalities unless those are static functionalities. But why we dont need to create a ArrayList object to use its methods like add, contains etc..
ArrayList<Egg> myList = new ArrayList<Egg>();
myList.add(a);
According to my understanding, myList is just variable which holds ArrayList object's reference of type ArrayList class. So again how can we write following without passing object to myList.
ArrayList<Egg> myList;
myList.add(a);
Complete code:
import java.util.ArrayList;
public class DotCom {
private ArrayList<String> locationCells;
public void setLocationCells(ArrayList<String> loc)
{
locationCells = loc;
}
public String checkYourself(String userInput)
{
String result = "miss";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
}
else
{
result = "hit";
}
}
return result;
}
//TODO: all the following code was added and should have been included in the book
private String name;
public void setName(String string) {
name = string;
}
}
PS
I am referring heads first java book.
The ArrayList reference is being set in the setter method:
public void setLocationCells(ArrayList<String> loc)
{
locationCells = loc;
}
If this method is not called, and the reference not set before trying to use the ArrayList, then the code will throw a NullPointerException.
Side note: This does not look to be safe code, since it can be easily run incorrectly and so a NPE is easy to create. Better perhaps to set the ArrayList (List is even better) in a constructor.
In a Android application I am making I have an array of instances of a certain class I made, and later in the program I need to use the getter and setter methods from that class on an instance of the class from the array. Do I need to assign the instance of the class from the array to a new class initializer? Here is some code to clear this up:
Class
public class ProfileInformation {
private String console;
private String gamertag;
public String getConsole() {
return console;
}
public void setConsole(String console) {
this.console = console;
}
public String getGamertag() {
return gamertag;
}
public void setGamertag(String gamertag) {
this.gamertag = gamertag;
}
}
Array
ArrayList<ProfileInformation> ProfTags = new ArrayList<>();
Some instances of ProfileInformation are then added to arraylist, and then I get one of the instances from the arraylist and try to use getGamertag() to set it to a string:
ProfileInformation profNew = ProfTags.get(ProfTags.size()-1);
String example = profNew.getGamertag();
The problem is example will equal null. Why is this?
First, an Arraylist is a List, try not to confuse that with actual arrays.
Do I need to assign the instance of the class from the array to a new class initializer?
You don't need to get an element out of the Arraylist, no. You can chain many methods together
String example = ProfTags.get(ProfTags.size()-1).getGamertag();
example will equal null. Why is this?
For the same reason any object is null... You never set it equal to anything else
This code runs on my laptop:
public static void main(String[] args) {
ArrayList<ProfileInformation> ProfTags = new ArrayList<>();
element = new ProfileInformation();
element.setGamertag("Actual Gamer tag value");
ProfTags.add(element);
ProfileInformation profNew = ProfTags.get(ProfTags.size()-1);
String example = profNew.getGamertag();
}
Output is:
Actual Gamer tag value
I guess you didn't call setGamertag(String).
First of all, this is part of a homework assignment, so please keep that in mind when answering.
So I am attempting to use a generic LinkedList class, which a CustomerList class inherits from. All code below is written by me and not given as part of the assignment.
I have written the customer type, which works successfully. The code shouldn't be needed, as the problem does not have to do with that class. It has 3 int fields, and a method to print it's info.
public void printCustomerInfo() {
System.out.println([int field 1, 2, 3]);
}
The issue has to do with the insert method (I believe) of the generic LinkedList class. It takes in a object of the determined class, and inserts it in the list in front of the current LinkedList object.
It does this by creating a copy of the current LinkedList object, setting that as the nextList, and then modifying the data of the current LinkedList object to the given dataIn.
Here is the code for the LinkedList class:
public class LinkedList<T> {
T data;
protected LinkedList<?> nextList;
public LinkedList() {
data = null;
nextList = null;
}
public boolean isEmpty() {
return (null == nextList);
}
public LinkedList<?> getNextList() {
return nextList;
}
public void insert(T dataIn) {
System.out.println("dataIn passed to insert method: \t" + dataIn);
LinkedList<T> tempList = new LinkedList<T>();
tempList.data = this.data;
tempList.nextList = this.nextList;
this.nextList = tempList;
this.data = dataIn;
System.out.println("data field of current object: \t\t" + data);
}
#SuppressWarnings("unchecked")
public T delete() {
T tempDump = data;
data = (T) nextList.data;
nextList = nextList.nextList;
return tempDump;
}
public void printInfo() {
if (isEmpty()) {
System.out.println("-END-");
} else {
System.out.println(data);
nextList.printInfo();
}
}
}
The CustomerList class extends it, and sets the data type to customer.
Here is the code:
public class CustomerList extends LinkedList<Customer> {
Customer data;
public void printInfo() {
if (isEmpty()) {
System.out.println("-END-");
} else {
data.printCustomerInfo();
nextList.printInfo();
}
}
}
Finally, the testing object:
public class GeneralTesting {
public static void main(String[] args) throws InterruptedException {
// Test LinkedList class
System.out.println(" - Create CustomerList and test methods");
CustomerList rList = new CustomerList();
System.out.println(" - Create a customer to store in the list");
Customer dude = new Customer(10, 65);
dude.setTimeServed(120);
System.out.println("proof that customer object exists: \t" + dude);
System.out.println(" - Insert customer into the list");
System.out.println("---method call: insert---");
rList.insert(dude);
System.out.println("---method end: insert----");
System.out.println("data in the list after return: \t\t" + rList.data);
}
}
This is what the console prints:
- Create CustomerList and test methods
- Create a customer to store in the list
proof that customer object exists: assignment3.Customer#3c250cce
- Insert customer into the list
---method call: insert---
dataIn passed to insert method: assignment3.Customer#3c250cce
data field of current object: assignment3.Customer#3c250cce
---method end: insert----
data in the list after return: null
As far as I can tell/understand, it is a scoping problem. Perhaps I am assigning the variable at a level that is ignored as the method resolves. I have run onto a similar issue before, and was able to resolve it, but cannot figure this out. Unfortunately, my prof is out town for next couple days, so I am looking for help here.
I just tried to make a method that simply sets the data field to a passed in object:
public void setData(T dataIn) {
this.data = dataIn;
}
Even this did not change the data from null. I know this must be due to not understanding Java generics correctly, so any pointers you can give, (and online resources to read) would be very appreciated.
Here's a hint. If you declare a data member in both the parent LinkedList class, and in the child class, the child member will overshadow the parent class's version.
I'm new to Android and Java but do have some experience in Objective C and iPhone programming. I'm attempting to recreate an app I've already designed for the iPhone and am getting stuck on what should be a simple concept.
In my ParserHandler class I am parsing an XML from a server and putting the data into three separate ArrayList's. The parsing appears to be working fine. When I log and iterate through the ArrayList within my ParserHandler.java class it all works fine.
(List1.java class has a few string variables and I've declared it like so in the ParserHandler: private List1 theList = new List1(); )
for(int i = 0; i<dogArray.size(); i++){
theList = dogArray.get(i);
Log.i(TAG, "looping " + i + " " + theList.Name);
Log.i(TAG, "looping " + i + " " + theList.PhotoUrl);
Log.i(TAG, "looping " + i + " " + theList.Type);
}//this loops fine and has all the data
The dogArray is declared like so: public ArrayList<List1> dogArray = new ArrayList<List1>();
Now I want to access the dogArray from the class DogListView.java so in the onCreate method I attempt to do the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dog_list_view);
ParserHandler ph = new ParserHandler();
int d = ph.getNumberofDogs();
int m = ph.dogArray.size();
Log.i(TAG, "dog size is:" + d + "and:" + m);}
I've tried two different ways and both always return "0" in the log. However the correct size is always logged and all the data is there when the log comes from the ParserHandler.java class.
This is the accessor method in ParserHandler.java.
public int getNumberofDogs(){
return dogArray.size();
}
I'd prefer to access the dogArray via accessor method (as this seems to be best practice from what I've gathered) however I'm open to all suggestions.
Thanks in advance!!
EDIT 8/23/12
I ended up solving the problem by declaring my ArrayLists Static. I know this (and public) approach my not be ideal for OOP but i'm going with it. In my ParserHandler.java I declared
public static ArrayList<List1> dogArray = null;
public static ArrayList<List1> otherArray = null;
public static ArrayList<List1> catArray = null;
Then begin my SAX parser:
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
super.startElement(uri, localName, qName, attributes);
if (qName.equalsIgnoreCase("ArrayOfDataFeedAnimal")){
catArray = new ArrayList<List1>();
dogArray = new ArrayList<List1>();
otherArray = new ArrayList<List1>();
}else if(qName.equalsIgnoreCase("DataFeedAnimal")){
theList = new List1();
}
then the rest of my SAX parsing stuff happens. Lastly, from whatever class I want to access the array i simply do that in the static way by ParserHandler.dogArray.size() to get the size of the array. I can now manipulate the array any way i see fit from whatever class i need to get it.
I'm still unclear why creating an instance of the ParserHandler class hasn't worked for me with my parsed ArrayLists because when it worked fine when I tested with a simple int[].
hopefully this can help someone else in the future.
Thanks again for everyones feedback!
Cheers!
you can do it in two ways,
Create a setter/getter class
Make a public static method that returns ArrayList
First Method:
class name : myDataObject.java
private ArrayList myArrayList;
// setting the ArrayList Value
public void setArrayList ( ArrayList myArrayList )
{
this.myArrayList = myArrayList;
}
// getting the ArrayList value
public ArrayList getArrayList()
{
return myArrayList;
}
Second Method:
In ArrayList file, ( suppose class name is class A.java )
private static ArrayList myArrayList = null;
...
// assign arraylist
public static ArrayList getArrayList()
{
return myArrayList;
}
in the calling activity/class you can call it using following code,
private ArrayList newArrayList = null;
newArrayList = A.getArrayList();
You should not make the Methods static.Because that is not an OOP Design then.
There are 2 ways:
1). Either make the properties public. (Not a good practise either)
2). add getters and setters for ParserHandler class
class ParserHandler {
private List<List1> dogArray = new ArrayList<List1>();
public List<List1> getDogArray() {
return this.dogArray;
}
public void setDogArray(List<List1> dogArray) {
this.dogArray = dogArray;
}
}
Now access dogArray Like this
ph.getDogArray();
int m = ph.getDogArray().size();
Initially it will be 0 since it is an empty list. Use the setter method to set the array first
Note that in your oncreate you are doing a file operation in your ParserHandler which parses the xml file as your data. This could potentially block the UI thread if the ParserHandler is not processed in a separate thread. However if you processed in a separate thread then your int d = ph.getNumberofDogs(); may return 0 even if there are data in your xml because of race conditions between UI thread and the separate thread processing the parsing.
The best solution in my opinion is to create a listener when the parsing is done so that you are pretty sure that the processing is done before you access the size of the list.
add this in your ParserHandler class
class ParserHandler {
...... your original codes here
private OnParsingDoneListener mListener;
public void setOnParsingDoneListener (OnParsingDoneListener listener){
mListener = listener;
}
public static interface OnParsingDoneListener {
public void onParsingDone (List dogList);
}
}
make sure to call mListener.onParsingDone when youre done parsing xml data.
In Your onCreate()...
ParserHandler ph = new ParserHandler();
ph.setOnParsingDoneListener (new ParserHandler.OnParsingDoneListener(){
public void onParsingDone(List dogList){
// do whatever you want to the doglist
// at this point all parsing is done and dogList contains the data from xml
}
});