What's wrong with this java code - java

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);
};

Related

How to load an arraylist of custom object through a function?

I'm probably stumbling on weak OO bases but how can I load elegantly an arraylist of my custom object trough a function in my main program?
I'd like it to look like it from the main:
ArrayList<MyObject> mylist = new ArrayList<MyObject>();
mylist.FetchFromDb();
I can't figure what would be the right thing to do:
extending the ArrayList class seems bad
method in main passed with the arraylist as an argument seems ugly
method in MyObject class doesn't work since mylist is an instance of arraylist
Of course i would be making connection to db and iterating over my resultset in that function, which I have no problem with for a standard object.
If you want to have a list that has such method, you should create your own class
class MyList<T> {
private ArrayList<T> storage = new ArrayList<>();
public void fetchFromDb() {
// ...
}
}
However I think you should create a separate function that fills the list, as a list function is not to fetch data from a database, but to provide functionality to store and retrieve elements.
You can't achieve that in Java without extending ArrayList or (even uglier, using delegate objects).
Not to say you cannot do this but you are talking about adding a method FetchFromDb() to Java's ArrayList object.
What would seem more appropriate to do is add to your object a FetchFromDb() which returns a list of the MyObject and then initialize the ArrayList with that.
public class MyObject{
//...
public static ArrayList<Node> FetchFromDb(){
//Code to get all the objects and add them to a list
//Return the list
}
}
Then you can call the static method
ArrayList<MyObject> mylist = MyObject.FetchFromDb();
The other option is to use a DAO which others have suggested and you can read about here

How to append items to ArrayList?

I've got a function to create syllables for words.
I use it like this: syllables(word1field); - creates List with syllables: aa,bb,cc
and syllables(word2field); - creates List with syllables: dd,ee,ff
And in the result I get dd,ee,ff, but I need aa,bb,cc,dd,ee,ff.
Is there possibility to append second list to first?
You get dd,ee,ff because when you call the same method again, it overrides the first ArrayList that is created.
The best thing you could do, that I can think of, is to make your ArrayList global because currently you just keep getting rid of the previous values and create a new ArrayList with the new values you give it. Try doing something like:
public class MyClass {
private List<String> myArray;
public MyClass() {
myArray = new ArrayList<String>();
}
public void syllables(wordfield) {
// do whatever you need to with wordfield
myArray.add(syllable);
}
I don't know how you've got everything laid out but this is the best solution I can think of.

Java: Calling a constructor of a class

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

Using ArrayLists as static properties in classes?

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.

Elements in java ArrayList taking up two places

I have made a LinkedList to store State objects which is a class I have created. I can add states to the list as expected, but whenever I try the size() method on the list it always returns twice the amount of elements I have added. Why is it doing this and how can I then use the get(n) method if each element has 2 values of n?
Here's the code used to create and add to the list:
static ArrayList<State> stateTable = new ArrayList<State>();
stateTable.add(new State(new Item(0,0)));
I will add that the adding to the list is done inside the constructor for State objects so that all created States get put in the stateTable.
Thanks
I will add that the adding to the list is done inside the constructor
for State objects so that all created States get put in the
stateTable.
If you already add the states to your list inside the constructor and additionally have the line
stateTable.add(
new State(new Item(0,0)) // <= first time inside new State(...)
); // <= second time explicitely in this line
then you are indeed adding it twice.
search for .add( and make sure you are not calling it in multiple places.
If your ArrayList is not marked as private mark it as private.
If you return your ArrayList from a method do return a read-only version via: Collection.unmodifiableList(stateTable);
If you load the data in one method or the constructor and do not intend to do it anywhere else than do it something like:
private static final List<State> stateTable;
static
{
final List<State> temp;
temp = new ArrayList<State>();
temp.add(new State(new Item(0,0)));
stateTable = Collections.unmodifiableList(stateTable);
}
Using the unmodifiableList will cause your program to crash if you add objects into it.

Categories