struggling a bit with something. I have built a proof of concept and googled but can't find reason.
I am currently trying to use an ArrayList as a static property in a class to store series of entries. The only problem is that everytime I try add to the Totalentries arraylist I get a nullPointerError.
Would appreciate some guidance as to where I am going wrong?
My Class:
import java.util.ArrayList;
public class Competition {
private static ArrayList totalentries;
public Competition(){
}
public void newEntry(){
totalentries.add("an Entry");
}
}
My Test Code:
public class testEntries {
/**
* #param args
*/
public static void main(String[] args) {
Competition myComp=new Competition();
myComp.newEntry(); //Null Pointer comes here!
myComp.newEntry();
myComp.newEntry();
myComp.newEntry();
myComp.newEntry();
myComp.newEntry();
myComp.toString();
}
}
You never instantiated totalentries in your Competition class.
You would need something like:
private static ArrayList totalentries = new ArrayList();
However, note that I would advise against keeping this "static". Otherwise, every "Competition" you create will be sharing the same list of entries, which is likely not what you really want.
Also, declare your types using interfaces, than instantiate with types. You may also want to use Generics here. So even better (and following standard naming conventions):
private List<String> totalEntries = new ArrayList<String>();
You never make an ArrayList. Try this:
private static ArrayList totalentries = new ArrayList();
though it would be better to use generics and get compile-time safety:
private static ArrayList<String> totalentries = new ArrayList<String>();
Since this list holds properties you wouldn't want it to be replaced so it would be even better if you were to define it like this:
private static final ArrayList<String> totalentries = new ArrayList<String>();
Really, though, none of these are good ideas because you could have multiple instances of your class changing totalentries at the same time. If that is your intent, that multiple Competitions use the one static totalentries for storage then you are better off keeping track of that data in a separate class.
If you are only using one Competition at a time then remove the static keyword.
totalentries is not initialized and it points to null. Make it like this:
private static List<String> totalentries = new ArrayList<String>();
The list must be created prior to usage, try
totalentries = new ArrayList();
You should also use List instead for the totalentries variable instead to allow exchanging te ArrayList with for example LinkedList.
Related
I want to know if there is a way to do this:
String **type** = "Player"
ArrayList<**type**> players = new ArrayList();
What I mean is defining an object type with a variable String. I put "player" and it can just be Player here, but what about a method that you can introduce a variable type to? Something like this:
public static void main (String[] args)
{
system.out.println("Select a type that u wanna make an array of");
system.out.println("1. Player");
system.out.println("2. Team");
Scanner in = new Scaner (System.in);
createArray(in.next());
}
public static void createArray(String **type**)
{
ArrayList<**type**> x = new ArrayList();
}
Is that possible?
Run away from Stringly-typed thinking and simply create your own class to capture all of the information you would want about a player.
public class Player {
// fields, methods to describe a player
}
public class Team {
// fields, methods to describe a team
}
Then, your ArrayList would work as you expect it to.
List<Player> players = new ArrayList<>();
List<Team> teams = new ArrayList<>();
As a side note: your current code structure would only create the list in that method and it wouldn't be available afterwards. If you want it back, you'd have to return ArrayList<Player>, or alternatively, declare it inside of main when you go to use it.
I am pretty sure it is possible with annotations and a custom annotation processor (but probably not a good idea).
Then your code would look like
#StringlyType String type="Player"
and you would would have to write a custom annotation processor that whenever it encounters a #StringlyType annotation creates a class as the other answers suggest.
But What is the Point?
Disclaimer: I have not actually tried any of this; nor do I intend to. So I can not guarantee it works.
There is no reason for doing this:
Generic types are only for compilation time type checking you need to understand this, they are not needed for what you are doing (determining the generic type at runtime).
You can simply do
List objects = new ArrayList();
and proceed to put any type into it but you will obviously have to cast the objects to the correct type before using them after taken out of the list.
private static final List<String> datas = new List<String>() {{
add("aaaa");
add("bbbb");
System.out.println(datas);
}};
I have declared a list and added some data. Then I want to print the data stored within that list. But the code does not work. Could you explain why?
You are using here what is refered to as double brace initialization. Basically, this creates an anonymous class with an initializer that does some processing, like adding data to the list.
Written with added line breaks, this is what it really looks like:
private static final List<String> datas = new List<String>() {
{
// this is the initializer block
add("aaaa");
add("bbbb");
System.out.println(datas);
}
// huh? no methods of List are implemented here!
};
The first problem is that you are trying to create an anonymous class of List but you are not overriding any of its abstract methods. This results in a compilation error.
The second "problem", is that the System.out.println class is inside the initializer, but as this moment, the variable datas is null, so that's will be printed (and that's probably not what you want).
So first, what you want is to create an anonymous class derived from ArrayList, or some other list implementation, so that you don't have to override any methods. Second, you don't want to print the content of the variable inside the initializer, but outside of it. Third, and probably most important: you don't want to use double brace initialization at all!
You need to implement the methods of the java.util.List interface. and your code is not inside a method or static block.
I think it's easier
// Creating an empty array list
ArrayList<String> list = new ArrayList<String>();
// Adding items to arrayList
list.add("Item1");
list.add("Item2");
Your code is implementing List interface as anonymous class, so you have to implement all List methods. I think you had in mind static list initialization that should be done like:
private static final List<String> datas = new ArrayList<String>();
static{
datas.add("aaaa");
datas.add("bbbb");
System.out.println(datas);
};
I have an ArrayList that holds objects of possibly different classes, and need to call the classes constructors.
ArrayList list = new ArrayList();
list.add(new Child1());
list.add(new Child2());
public void Spawn(){
Class clazz = list.get(0).getClass();
list.add(clazz.getConstructor().newInstance());
}
How can I achieve this? The last line in the code returns an error because the clazz.getConstructor().newInstance() returns an object, not an instance of child1. The different list items will all have a common parent, and in fact the items on the list can even all be the same, but i just can't hard-code the class name into the program.
Edit:
I may have stripped down the example too far.
I basically have a class that manipulates ArrayLists and needs to add new instances of the objects already inside, but the list may have different class types inside of it.
Edit:
Based on everyones responses, this is obviously the wrong way to approach the problem!
I think I will try a cloning method for the objects inside the lit, but I'll also look for a different approach entirely.
Thanks for the help.
This works just fine:
public static void arraylist() throws Exception {
ArrayList list = new ArrayList();
list.add(new X());
Class clazz = list.get(0).getClass();
list.add(clazz.getConstructors()[0].newInstance());
}
And I'm not saying you should use it..
I want to be able to make an array list of objects, and then be able to edit and read back some simple properties of each object. In this case, a String (colour) and integer (X). I can't seem to make the simple code below work. Note that I am aware people sometimes use the <> notation with array lists, but I have read that it should be possible without, and at the moment I am very new to Java and wish to keep things as simple as possible.
At the moment I get an error on the line which is commented out (cannot find symbol X)
import java.util.ArrayList;
public class ArrayList_of_Objects {
public static void main(String[] args)
{
ArrayList al = new ArrayList();
for(int i =0;i<5;i++)
{
MyObj ob1 = new MyObj();
ob1.X = i + 5;
al.add(ob1);
//System.out.println("X: "+al.get(i).X);
}
for(int j=0;j<5;j++)
{System.out.println("X: "+al.get(j).X);}
al.get(3).X=4;
al.get(3).colour="orange";
System.out.println(al.get(3).X);
System.out.println(al.get(3).colour);
}
}
class MyObj
{
int X;
String colour;
}
Yes, you need to use generics to say what kind of object will be in your list:
ArrayList<MyObj> al = new ArrayList<MyObj>();
Otherwise the compiler doesn't know that al.get(3) is meant to return a MyObj rather than just anything. With this code, it will not only fix the get calls - it will stop you from accidentally adding objects of inappropriate types to the list.
Also, it's usually preferred to declare variables as an appropriate interface type, such as:
List<MyObj> al = new ArrayList<MyObj>();
(There are times where you really need it to be the concrete type, but generally prefer programming to interfaces.)
Generics is a massive topic, but the tutorial linked at the start of this answer should get you going. The Java Generics FAQ is a great resource for finding out more.
Change
ArrayList al = new ArrayList();
to
ArrayList<MyObj> al = new ArrayList<MyObj>();
What you have right now is an array list of Object rather than an array list of MyObj, and Object has no knowledge of MyObj.X.
Use ArrayList<MyObj> al = new ArrayList<MyObj>(); instead
Can anyone please explain me in which scenario we use static initial block?
You can use it as a "constructor" for static data in your class. For example, a common situation might be setting up a list of special words:
private static final Set<String> special = new HashSet<String>();
static {
special.add("Java");
special.add("C++");
...
}
These can then be used later to check if a string matches something interesting.
The most common scenario is loading some resources on class load, for example loading library for JNI
And another common one is when some of the code you need to use to create your statics throw exceptions.
Another example is java.lang.Object
public class Object {
private static native void registerNatives();
static {
registerNatives();
}
...
I use them all the time to initialize lists and maps.
List<String> myList = new ArrayList<String>(){{
add("blah");
add("blah2");
}};
for(String s : myList){
System.out.println(s);
}