How to append items to ArrayList? - java

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.

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

What's wrong with this java code

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

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

Java - ArrayList<Integer> as Parameter...?

I would like to know how to create a method which takes an ArrayList of Integers (ArrayList) as a parameter and then display the contents of the ArrayList?
I have some code which generates some random numbers and populates the ArrayList with the results, however I keep having errors flag up in eclipse when attempting to create this particular method.
Here is what I have so far:
public void showArray(ArrayList<Integer> array){
return;
}
I know that it is very basic, but I am unsure exactly how to approach it - could it be something like the following?
public void showArray(ArrayList<Integer> array){
Arrays.toString(array);
}
Any assistance would be greatly appreciated.
Thank you.
I'm assuming this is a learning exercise. I'll give you a few hints:
Your method is named showArray, but an ArrayList<T> is of type List<T>, and is not an array. More specifically it is a list that is implemented by internally using an array. Either change the parameter to be an array or else fix the name of the method.
Use an interface if possible instead of passing a concrete class to make your method more reusable.
Minor point: It may be better to have your method return a String, and display the result outside the method.
Try something like this:
public void printList(List<Integer> array) {
String toPrint = ...;
System.out.println(toPrint);
}
You can use a loop and a StringBuilder to construct the toPrint string.
Is there any reason why System.out.println( array ); wouldn't work for you?
Output will be like:
[1, 2, 3]
If you are looking to print the array items, try
public void showArray(ArrayList<Integer> array){
for(int arrayItem : array)
{
System.out.println(arrayItem);
}
}
This sounds like someone wants us to do their homework. You don't have to return anything if you are just displaying it, and if the method has a void return type. I don't know exactly what you want but is it something along the lines of System.out.println(array.elementAt(index))? then you would need a loop.

Adding elements to an array?

here i am trying to add elements to the array.
the elements i am trying to add are text fields, so im basically trying to store persons contact details within the array list?
any help would be greatful
public void addContact()
{
ArrayList<String> details = new ArrayList<String>();
{
details.get(txtname(0));
details.get(txtnum(1));
details.get(txtmob(2));
details.get(txtadd1(3));
}
}
It sounds like you haven't thought out the entire problem yet.
Adding elements to an ArrayList in Java is done like this:
public void addContact(){
ArrayList<String> foo = new ArrayList<String>();
foo.add("HELLO");
foo.add("WORLD");
}
yankee2905 explains it very well; that's what you need to get your code to work with an ArrayList.
As a side note, you're not dealing with an array, you're dealing with an ArrayList. For an array, you might have something like this:
String[] details = new String[4];
details[0] = "First";
details[1] = "Second";
details[2] = "Third";
details[3] = "Last";
It almost sounds like you're trying to use an ArrayList to store contact information for multiple people. If that is the case, you will probably want to do it a bit differently. You can create a Contact object that has members for each piece of information you want to store (e.g. firstname, lastname, phone, mobile, address1, address2, etc). Then you can just add Contact objects to your ArrayList like:
Contact contact1 = new Contact();
contact1.setFirstname("Bob");
myArrayList.add(contact1);
public void addContact()
{
ArrayList<String> details = new ArrayList<String>();
{
details.add(//Insert value from post here);
details.add(//Insert value from post here);
details.add(//Insert value from post here);
details.add(//Insert value from post here);
}
}
I've not used java in a while maybe someone will add to this.
You need set or add, not get. See the docs here.
And to get the text from the textfields, use getText.
So you'd have something like:
myArrayList.add(myTextField.getText());
You are trying to use inbuilt array initializer syntax. That does not work on container classes (unless its some new fangled way in c#) you need to use details.add() (or the appropriate member function).
The syntax you are trying to use is for the language supported hardwired array types. In C++ this would look like char x[6] = {'h','e','l','l','o'};. However a container is not an array its a container object. Container objects often mimic arrays by overloading operator[] however they use different data structures behind the scenes -- i.e., they do not use contiguous regions of memory.
p.s., If this was c#.NET -- which I initially assumed -- there is a new mechanism to map array initialization to container object creation. I'll leave it down there for anyone that is interested.
in C# 3.5 using array initializer syntax you can do the following :
public void addContact()
{
ArrayList<String> details = new ArrayList<String>()
{
details.get(txtname(0)),
details.get(txtnum(1)),
details.get(txtmob(2)),
details.get(txtadd1(3))
}
}
Gotta love Microsoft and C# :P
public void addContact()
{
ArrayList<String> details = new ArrayList<String>();
details.add(txtname.getText());
details.add(txtnum.getText());
details.add(txtmob.getText());
details.add(txtadd1.getText());
}
Sorry I don't have an IDE open, but I think this is closer to what you are after.
I think this is the best solution if you want to create an array with some elements:
String[] images = {"a.png","b.png","c.png"};
or
String[] images;
images = new String[]{"a.png","b.png","c.png"};

Categories