3

Is it possible to add objects into an Arraylist through a for-loop?

I would like to shorten down the code! or do you have any other tips on how to create a word quiz with different classes and methods?

I have three classes, Main that drives the game, Quiz where the game is constructed, and a class with the Dictionary with all the words.

ArrayList<Sweng> Wordlist = new ArrayList<Sweng>();

Sweng s1 = new Sweng("bil", "car");
Sweng s2 = new Sweng("blå", "blue");
Sweng s3 = new Sweng("baka", "bake");
Sweng s4 = new Sweng("hoppa", "jump");
Sweng s5 = new Sweng("simma", "swim");
Sweng s6 = new Sweng("måne", "moon");
Sweng s7 = new Sweng("väg", "road");
Sweng s8 = new Sweng("snäll", "kind");
Sweng s9 = new Sweng("springa", "run");
Sweng s10 = new Sweng("hus", "house");


Wordlist.add(s1);
Wordlist.add(s2);
Wordlist.add(s3);
Wordlist.add(s4);
Wordlist.add(s5);
Wordlist.add(s6);
Wordlist.add(s7);
Wordlist.add(s8);
Wordlist.add(s9);
Wordlist.add(s10);
Software Engineer
  • 15,457
  • 7
  • 74
  • 102
emma
  • 47
  • 4

5 Answers5

2

You can define two different string arrays, each containing the string data for each field of your Object class:

String [] array1 = {"bil", "blå", "baka", "hoppa", ... };
String [] array2 = {"car", "blue", "bake", "jump", ... };

And then add the Objects to the Wordlist as follows:

ArrayList<Sweng> Wordlist = new ArrayList<Sweng>();
for (int i=0; i<array1.length; i++)
    Wordlist.add(new Sweng(array1[i], array2[i]));
GURU Shreyansh
  • 881
  • 1
  • 7
  • 19
  • Although this looks good and has good performance, it can also be fragile: if someone in future adds N Swedish words to array1 and (N-1) English translations to array2 (missing out one translation) then _all_ the following translations will be wrong. – k314159 Jul 15 '21 at 09:40
2

Here's an example of how to do this with java streams, though, given your current level in java I wouldn't recommend using this answer unless you're doing this professionally because it's a bit on the advanced side.

import java.util.Arrays;
import static java.util.stream.Collectors.toList;
import java.util.List;

class Sweng {
    Sweng(String a, String b) {}
}

public class Main{

     public static void main(String[] args){
        List<Sweng> swengs = Arrays.stream(new String [][]{
          {"bil", "car"},
          {"blå", "blue"},
          ...
        }).map(t -> new Sweng(t[0], t[1])).collect(toList());
     }
}

You can add new elements to the list where the ellipsis are ('...') and that can be of any length.

Software Engineer
  • 15,457
  • 7
  • 74
  • 102
  • Don't get me wrong, but I really don't understand why you propose the answer which you don't recommend to use.. or why not to explain more - if it's still proposed?.. to me, personally, this seems a bit overburdened. – Giorgi Tsiklauri Jul 15 '21 at 08:55
  • I suspect that the OP is doing this as an exercise for some class, and I don't want them to get into trouble by clearly copying the answer from some pro java engineer on StackOverflow. However, it's worth putting the answer here for other more senior engineers who need a solution to this problem in a professional setting and who find this answer on SO. I'll update the answer to be clearer on this point, thanks. – Software Engineer Jul 15 '21 at 08:57
1

Not using a for-loop but this may help you nonetheless.

ArrayList<Sweng> Wordlist = new ArrayList<Sweng>();

Wordlist.add(new Sweng("bil", "car"));
Wordlist.add(new Sweng("blå", "blue"));
Wordlist.add(new Sweng("baka", "bake"));
Wordlist.add(new Sweng("hoppa", "jump"));
Wordlist.add(new Sweng("simma", "swim"));
Wordlist.add(new Sweng("måne", "moon"));
Wordlist.add(new Sweng("väg", "road"));
Wordlist.add(new Sweng("snäll", "kind"));
Wordlist.add(new Sweng("springa", "run"));
Wordlist.add(new Sweng("hus", "house"));
Vasconcelos
  • 300
  • 2
  • 9
  • How is this different from the question other than the fact that extra variables aren't created? ;) – PsyGik Jul 15 '21 at 08:41
  • OP clearly states "I would like to shorten down the code!" ;) – Vasconcelos Jul 15 '21 at 08:42
  • lol, you got me there! But OP also mentions a for-loop, so the answer is incomplete – PsyGik Jul 15 '21 at 08:43
  • Without any other information regarding the source of the data OP intends to add to their ArrayList there's no way I can provide an answer using a for-loop. If OP stated that the data came from a file, was retrieved from an auxiliary array or something like that I could provide a more detailed answer. Without more information, this is the help I can provide. – Vasconcelos Jul 15 '21 at 08:47
1

Let's reconsider and contemplate on what you're asking for.

Definitely, it is possible to contract and shorten several lines of the instantiation and adding code, per se, that is:

Sweng s1 = new Sweng("whatever..", "whatever..");
...
Sweng sk = new Sweng("whatever..", "whatever..");

instance.add(s1);
...
instance.add(sk);

but wait a moment.. and pay close attention to how you instantiate objects that you later add into your list.

Where that data comes from? any systematic read-process?

No.

You just have hard-coded whatever comes to your mind (or is asked in your task) and there is no way, any program, in the world, can guess what that data should be.

Alternatively, you can create a simple text file, and write in it your data, with some conventional formatting (let's say, one entry at a line). Then, sure enough, you can read that file and populate respective objects - hence, add them into your list - in just a simple loop construct.

Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66
0

Snippet 1

List<Sweng> Wordlist = Arrays.asList(
    new Sweng("bil", "car"),
    new Sweng("blå", "blue"),
    new Sweng("baka", "bake"),
    new Sweng("hoppa", "jump"),
    new Sweng("simma", "swim")
    new Sweng("måne", "moon")
    new Sweng("väg", "road")
    new Sweng("snäll", "kind")
    new Sweng("springa", "run")
    new Sweng("hus", "house")
);

Snippet 2

List<Sweng> Wordlist = List.of(
    new Sweng("bil", "car"),
    // ...
);

Snippet 3 (antipattern) Double Brace initialization

List<Sweng> list = new ArrayList<Sweng>() {{
    add(new Sweng("bil", "car"));
    // ...
}};
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
  • 2
    I wouldn't really suggest [double brace initialization](https://stackoverflow.com/questions/1958636/what-is-double-brace-initialization-in-java) without a comment. It's not necessary here and I personally consider it an anti-pattern. – Joachim Sauer Jul 15 '21 at 09:12