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.
Related
I have a class to generate an Arraylist it all seems to work but in main it produces a compilation problem which I guess does not recognize my variable name as an ArrayList
public class Order {
//Attributes
private ArrayList<DessertItem> order;
//Constructors
Order(){
order = new ArrayList<DessertItem>();
}
//Methods
public ArrayList<DessertItem> getOrderList(){
return order;
}//end of getOrderList
public void add(DessertItem aItem) {
order.add(aItem);
}//end of add
public int itemCount() {
return order.size();
}//end of itemCount
}//end of class
public class DessertShop {
public static void main(String[] args) {
//create order
Order order = new Order();
//create obj and adding to the order
Candy c1 = new Candy("Candy Corn", 1.5, .25);
order.add(c1);
for (DessertItem item : order) {//here is where is marked the error
System.out.printf("%s.%n", item.getName());
}
Your code is hard to read. I'd recommend paying attention to formatting.
order is an Order, not an ArrayList. It has an ArrayList. That's what you want to iterate over.
Try this:
for (DessertItem item : order.getOrderList()) {
System.out.printf("%s.%n", item.getName());
}
A lot of your comments are clutter. I'd remove them.
I'd prefer a static type of List<DessertItem> for order. You can change the implementation for the List if you need to.
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.
I have a class named Preprocessing and has a method called Process()
, it has an ArrayList called datatweets that contains my data.
public void Process(){
//the process...
datatweets.add(mydata);
}
then I try to pass the datatweets and the value(my data) to another ArrayList on the different class. I've tried using getter method such as:
public ArrayList getMyList(){
return datatweets;
}
but it still doesn't print any value when I call it. please tell me what is wrong, and what should I do?
here's what i do to call the arrayList:
Preprocessing data = new Preprocessing();
ArrayList<String> dataset = new ArrayList<>();
dataset = data.getMyList();
for(int a=0;a<dataset.size();a++){
System.out.println(dataset.get(a));
}
As i understand you have an class named "Preprocessing". Now you should have "datatweets" as your instance variable of the class.
Now you should create an object of Preprocessing and call the method "Process". In the method process you should fill the arraylist "datatweets". Process method should contain below code.
if(this.dataTweets == null)
this.dataTweets = new ArrayList<>();
this.dataTweets.add(myData);
Once the datatweets is filled by calling the process method. You should have getter method in same class which should return datatweets
public List<String> getDataTweets(){
return this.dataTweets;
}
Now the main function should look like this
public static void main(String[] args){
Preprocessing preprocessor = new Preprocessing();
preprocessor.Process();
List<String> dataTweets = preprocessor.getDataTweets();
//Now iterate over this you will surely get data.
}
You class Preprocessor should be like this
public class Preprocessor{
private List<String> dataTweets;
public void process(){
//processing
this.dataTweets.add(data);
}
public List<String> getDataTweets(){
return this.dataTweets;
}
}
How can I access list of one class in another class using Java.
I'm getting an empty list by using the following code.
My code :
public class DataRead {
public static List<String> list = new ArrayList<String>();
public void readData() {
list.add("abc");
list.add("xyz");
}
}
public class GetListData {
public static void main(String[] args) {
List<String> getList = DataRead.list;
System.out.println(getList); //getting null
}
}
My edited code:
public class GetListData {
public static void main(String[] args){
DataRead dataRead = new DataRead();
dataRead.readData(); //Add elements to list
List<String> myList = DataRead.list;
System.out.println(myList.get(0));
}
}
Still getting empty set after editing the code.
You need to actually call readData() method first, which fills your List, e.g.
public static void main(String[] args) {
new DataRead().readData();
List<String> getList = DataRead.list;
System.out.println(getList);
}
After OP's edit:
I doubt you're getting an empty result - check it out on ideone.
The problem is that, the list is still empty. To read from the list, you need to get specific element out from it:
list.get(x); //where x is an int value
The reason the list has no elements added is because the statements for adding into the list resides in readData method. You need to invoke the method first:
DataRead dataRead = new DataRead();
dataRead.readData();
So to read the elements, you can go with this:
public static void main(String[] args){
DataRead dataRead = new DataRead();
dataRead.readData(); //Add elements to list
List<String> myList = DataRead.list;
System.out.println(myList.get(0)); //getting "abc"
}
If list is not meant to be shared, but as a property of individual DataRead object, I would do it as:
class DataRead
{
//Your other attributes..
private List<String> list;
public DataRead(){
list = new ArrayList<String>();
}
public <ArrayList> getList(){
return list;
}
public void addToList(String s){
list.add(s);
}
}
Change your code to this.
public class DataRead {
public List<String> list;
public void DataRead() {
list = new ArrayList<String>();
list.add("abc");
list.add("xyz");
}
}
And use it as follows.
public class GetListData {
public static void main(String[] args) {
DataRead d = new DataRead();
List<String> getList = d.list;
System.out.println(getList); //getting null
}
}
The best approach would be to use Getters and setters and do not make the variables static, unless and until its required.
From reading tutorials and practicing Java, I have come across a problem. I have created a String ArrayList, added string to it. However I want one method which allows me to add more string to this arrayList and another method which allows me to display this arrayList. below is my attempt to solve this problem. My code only prints an empty Array List
class apples {
public static void main(String[] args) {
viewArrayList(); //prints a empty arraylist
}
public static void addString() {
ArrayList<String> destinationArray = new ArrayList<String>();
destinationArray.add("example1");
destinationArray.add("example2");
}
static ArrayList GetArrayList() {
ArrayList<String> destinationArray = new ArrayList<String>();
return destinationArray;
}
public static void viewArrayList() {
System.out.println(GetArrayList());
}
}
Didn't you forget adding addString() to getArrayList()?
Your variable destinationArray is declared in a method, it meens that it only exists inside this method outside addString() the object does not exist anymore and you can't access it in other methods. To do it you have to declare it as a class variable like that :
class apples{
ArrayList<String> destinationArray = new ArrayList<String>();
public static void main(String[] args)
When your program is executed, in fact it executes the main method, as a result if you want to execute your method addString() you will have to call it in the main function. It will look like that :
public static void main(String[] args)
{
this.addString();
this.viewArrayList(); //prints a empty arraylist
}
Create a Object of a ArrayList and pass reference to different methods. Example create a ArrayList Object in main class and pass it to addString & display method.
public static void main(String[] args){
List<String> destinationArray = new ArrayList<String>();
viewArrayList(destinationArray);
displayArrayList(destinationArray);//prints a empty arraylist
}
public static void addString(List destinationArray ){
destinationArray.add("example1");
destinationArray.add("example2");
}
...
I would do something like this:
class apples
{
private ArrayList<String> array = new ArrayList<String>();
public void addString(String addString)
{
this.array.add(addString);
}
public ArrayList<String> GetArrayList()
{
return array;
}
}
One problem is that you use a different array list for each method. Every time you use the keyword new you are creating a new (and empty) list.
At the top of your class create the ArrayList once...
private ArrayList<String> myList = new ArrayList<String>();
then refer to myList in all your other methods without assigning it a new value.
public ArrayList<String> getArrayList() {
return myList;
}
public void addSomeStrings() {
myList.add("Some String");
myList.add("Some Other String");
}
and don't be afraid to walk through a Java tutorial. This is a fundamental concept and you may get pretty frustrated if you don't shore up your foundation.
Compile and run following program.
import java.util.ArrayList;
class Apples {
static ArrayList<String> destinationArray = new ArrayList<String>();
public static void main(String[] args) {
System.out.print("First time");
viewArrayList();
addString("Example1");
addString("Example2");
addString("Example3");
System.out.print("Second time");
viewArrayList();
addString("Example4");
addString("Example5");
System.out.print("Third time");
viewArrayList();
}
public static void addString(String example) {
destinationArray.add(example);
}
static ArrayList getArrayList() {
return destinationArray;
}
public static void viewArrayList() {
System.out.println(getArrayList());
}
}
The scope of the array object is the problem here. You are adding string to 1 array and trying to print another array. Remove the static block and the array declaration in addString(). Declare the array next to the class definition like this,
class apples {
ArrayList destinationArray = new ArrayList();
.. ....
It should work.
Code:
public class Apples {
public static void main(String[] args) {
viewArrayList(); //prints a empty arraylist
}
public static ArrayList<String> addString() {
ArrayList<String> destinationArray = new ArrayList<String>();
destinationArray.add("example1");
destinationArray.add("example2");
return destinationArray;
}
public static ArrayList<String> GetArrayList() {
return addString();
}
public static void viewArrayList() {
System.out.println(GetArrayList());
}
}
Output:
[example1, example2]