Java Program throws NullPointerException [duplicate] - java

This question already has answers here:
NullPointerException when Creating an Array of objects [duplicate]
(9 answers)
Closed 8 years ago.
I'm trying to write a program to create a media object, I created the Cassette class which inherits from Audio which inherits from Media. I'm getting a null pointer exception and I have been trying for hours to fix it but I have no idea why it's being thrown. I appreciate your help in advance, thank you.
In my application class I initiate the following:
static Media[] collection = new Media[100];
And later on in the code I try to create a new Cassette object but it gives me the said null pointer exception.
The code I have is:
collection[collection[0].getNumItems()] = new Cassette(cTitle, cMajorArtist, cPlayingTime, cNumPlays, cNumGroupMembers, cGroupMembers, pArtist, cNumSongs, cSongs);
All of the items being passed into the Cassette are all user input data. It compiles fine but it's just when I run it that I get an error.
EDIT
Here is the numItems value in my media class.
static int numItems = 0;
And the method to return the number of items:
public int getNumItems()
{
return numItems;
}
Thanks.

I suggest you use a Collection like ArrayList. With the diamond operator that would look something like,
static List<Media> collection = new ArrayList<>();
Then you can use List#add(E)
collection.add(new Cassette(cTitle, cMajorArtist, cPlayingTime,
cNumPlays, cNumGroupMembers, cGroupMembers, pArtist, cNumSongs, cSongs));
Edit If you want to use the array type, then this
collection[collection[0].getNumItems()]
Should be
collection[Media.getNumItems()]
To call the static getNumItems() in Media. Which should be
public static int getNumItems()
{
return numItems;
}

Related

Convert a list of functions to can passed to a varargs method arguments [duplicate]

This question already has answers here:
How to pass an ArrayList to a varargs method parameter?
(5 answers)
Closed 4 years ago.
public Email myMethod(Function<MyObject, String>... functions) { ... }
I created a list of functions and I want to passed to myMethod:
List<Function<MyObject, String>> functions= new ArrayList<>();
if (condition1) {
functions.add(myObject->myObject.getStringX());
} else {
functions.add(myObject->myObject.getStringY());
}
myMethod(functions);//Does not compile, I must find a solution here
to convert my list of functions to an array that can be accepted as
myMethod argument
It's an array of functions, so create an array of such functions and pass it.
Or you can call it with:
Function<MyObject, String>[] array = new Function[functions.size()];
functions.toArray(array);
myMethod(array);
Just notice that you can not create a generic array, but you can declare one as such.
A cleaner code I believe could've been
Function [] functionsArray = new Function[functions.size()];
for (int i=0;i< functions.size();i++) {
functionsArray[i] = functions.get(i);
}
myMethod(functionsArray); // unchecked assignment here ofcourse
which then my IDE suggests me to write as
myMethod(functions.toArray(new Function[0]));

Why am I able to modify a List in a method that's out of scope, without returning it? [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
Let's say I initialise my list like so:
public static void main(String[] args) {
ArrayList<String> a = new ArrayList<String>();
a.add("one");
a.add("two");
a.add("three");
a.add("four");
modifyList(a);
}
where modifyList simply changes every value to "one" like so:
private static void modifyList(ArrayList<String> a) {
for (int i = 0; i < a.size(); i++) {
a.set(i, "one");
}
}
If I print the list before and after I call this method, I expect the same original list to appear twice. But for some reason, the ArrayList that gets modified in modifyList is the same as the ArrayList in main.
If I try the same experiment with ints and Strings instead of Lists they do not get modified.
Can anyone explain why?
In Java, parameters are passed by value.
However, you passed a reference to your ArrayList to the method (and the reference itself is passed by value), and therefore the method modified the original list.
If you want to ensure that this cannot happen, you need to pass an immutable list as the parameter.

Appending List to List [duplicate]

This question already has answers here:
Add ArrayList to another ArrayList in java
(6 answers)
Closed 7 years ago.
I'm writing a class called List which creates an instance variable array of Customers (Customer is just another class that accepts String parameters for a person's name),
i.e private Customer[] data
I'm trying to write an append method that will take a Customer and add it to another List in the main method.
To do this, there seems to be a method called addAll(), but since I'm writing this code by scratch, I can't use this. I looked at the pseudo code though for this method to get a general idea and it converts the Object into an array and then uses arraycopy to append the two lists.
I meant to say, this way makes sense to me, if I were using arrays, but I'm trying to add a Customer object from another list and add them to a list in the main method.
Not sure of what you want, but I think you can implement the append method yourself just as what the arraycopy method do. Here is a simple example
class List {
private int size;
private Customer[] data;
private final static int DEFAULT_CAPACITY = 10;
public List() {
size = 0;
data = new Customer[DEFAULT_CAPACITY];
}
public void append(List another) {
int anotherSize = another.size;
for (int i = anotherSize - 1; i >= 0; --i) {
if (size < data.length) {
data[size++] = another.data[i];
another.data[i] = null;
another.size--;
} else {
throw new IndexOutOfBoundsException();
}
}
}
}

How do I give a predetermined name to an object? [duplicate]

This question already has answers here:
Assigning variables with dynamic names in Java
(7 answers)
Closed 8 years ago.
I am trying to create a method that contains a for loop that creates new objects, but I am stuck at how to assign a predetermined name to an object based on the loop's count. For instance it would be something like this:
private void createPictureObject(int count){
for(int a = 1; a <= count; a++){
Picture picture*a* = new Picture(arguments);
}
The result of this loop would be that I have objects named something like picture1, picture2, picture3, picture 4 etc. Is this even possible?
No You cannot do that! Dynamic variable naming is not allowed in Java. Use an array instead.
Picture[] pictures = new Picture[10];

Sharing an ArrayList<Custom> in Android Application [duplicate]

This question already has answers here:
What's the best way to share data between activities?
(14 answers)
Closed 9 years ago.
I have a json file. So, I was parsed the json file and I stored all value in an ArrayList. Now, I want to share the value all the classes in application. So, what is recommended and efficient way to do that??
Singleton pattern.
just create a public static reference for your List object and access it from any part of your app. it will be accessible as long as your app is alive. and you can deallocate it manually (by nulling the reference).
public class SharedData {
public static List<Custom> jsonData;
}
and from any part of your application:
SharedData.jsonData = new ArrayList<Custom>();
and to read the data
Custom obj = SharedData.jsonData.get(0);
Singleton wiki
Now, I want to share the value all the classes in application. So, what is recommended and efficient way to do that??
Assuming that you missed out a preposition "with" in your above question and want to use your arraylist in all other classes as well, you might wanna go for a global Arraylist, which is nothing but declaring a public static Arraylist in a new class (let's call it GlobalState.java).
/** GLobalState.java **/
public class GlobalState {
public static ArrayList<E> jsonGlobalArrayList;
}
You can use getters & setters if you want.
Now, u can assign your arraylist to this global Arraylist as soon as u have populated your arraylist after parsing the json file.
GlobalState.jsonGlobalArrayList = jsonArrayList;
This is how I do it whenever I'm dealing with json values. Hope this helps.
P.S.: Excuse me for oversimplifying the solution this elaborately, as u might have understood this already when I mentioned about global ArrayList. :)
public class Utilities {
public static boolean boolVar = false ;
public static int intVar= 0 ;
public static String str = "" ;
public static List<Object> aList= new ArrayList<Object>() ;
public static HashMap<String, Object> aMap= new HashMap<String, Object>() ;
}
Use them by using class name like;
Utilities.boolVar = boolValue ; Utilities.intVar = intValue ;
inside activities.

Categories