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..
Related
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
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'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.
I am writing a Linked List class that takes in names or numbers, and then prints them out in a list. I managed to write the list normally. Here is what I did:
public String toString(){
return list.toString; //where list is the LinkedList I am calling
}
That works correctly and returns my list after adding 4 elements like this:
[Joe, Jessica, Max, 5]
Now I am trying to convert that same method onto a generic method, so I did 2 things.
Here I created the collections object:
private Collection<E> collection;
public MyLinkedListG(Collection<E> _collection) {
collection= _collection;
}
And here is how I wrote the new toString in collections:
public String toString(){
StringBuilder builder = new StringBuilder();
for(E e : collection) {
builder.append(e); //appends each string
}
return builder.toString();
}
The problem is that now my test class will not allow me to call the LinkedList object I had created before which was:
MyLinkedListG x = new MyLinkedListG();
It states I need to input a collection inside the parameter. How can I call it now? Or am I doing it totally wrong?
If something is not clear please let me know so I can clarify as soon as possible. Thanks in advanced.
From what I can tell, your original class likely did not include a constructor. This means the no-arguments constructor new MyLinkedListG() is provided by default, which is likely what you used to construct an instance of your class.
After your modifications, you added a constructor MyLinkedListG(Collection<E> _collection). Now the no-arguments constructor is not provided by default anymore. If you want to continue to use it, it must be explicitly defined.
Your class will probably have two (or more) constructors in this case, perhaps something like this:
private Collection<E> collection;
public MyLinkedListG(Collection<E> _collection) {
collection= _collection;
}
public MyLinkedListG() {
collection=new LinkedList<E>();
}
Now you can use either constructor for your object.
You can only use an empty constructor if
A) you have not defined a constructor
or
B) if you have explicitly defined an empty constructor.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.8.9
As you can see I have a StaffMember class and trying to make a list of StaffMember objects, but when I go to get them out of the list I get errors. What could be causing this (Or java lists are different from other languages).
Since you're not using a generic List variable, the compiler has no way of knowing what type of objects the List contains, and so you'll have to cast the object returned by the get(...) method to the type you believe it to be.
A better solution is to declare your list variable to be a generic List<StaffMember>.
public class StaffList {
private List<StaffMember> list;
I think your life will be better if you do it this way:
public class Staff {
private List<StaffMember> roster;
public Staff() {
this.roster = new ArrayList<StaffMember>();
}
// add the rest
}