-4

I'm writing come boilerplate like this:

    this.lposItems = new LposItems[5];
    final LposItems lposItem = new LposItems();
    lposItem.setA("24341");
    lposItem.setB("14");
    final LposItems lposItem1 = new LposItems();
    lposItem1.setA("62");
    lposItem1.setB("49");
    final LposItems lposItem2 = new LposItems();
    lposItem2.setA("40");
    lposItem2.setB("4");
    final LposItems lposItem3 = new LposItems();
    lposItem3.setA("62");
    lposItem3.setB("63");
    final LposItems lposItem4 = new LposItems();
    lposItem4.setA("14");
    lposItem4.setB("4");
            final LposItems lposItem5 = new LposItems();
    lposItem5.setA("15");
    lposItem5.setB("4");


    this.lposItems[0] = lposItem;
    this.lposItems[1] = lposItem1;
    this.lposItems[2] = lposItem2;
    this.lposItems[3] = lposItem3;
    this.lposItems[4] = lposItem4;
            this.lposItems[5] = lposItem5;

Can someone tell me of any 3rd party lib that can reduce this? (like a readymade builder or some other technique)

user2666282
  • 381
  • 1
  • 2
  • 15

2 Answers2

5

I'm not sure why you'd want a 3rd party library when Java provides you with all you need in the language for this. For example, you could create a static factory, like the following

private static LposItems createLposItems(String a, String b) {
    LposItems lposItems = new LposItems();
    lposItems.setA(a);
    lposItems.setB(b);
    return lposItems;
}

then populate your array like this:

this.lposItems = {
    createLposItems("24341", "14"), 
    createLposItems("62", "49"), 
    createLposItems("40", "4"), 
    createLposItems("62", "63"), 
    createLposItems("14", "4"), 
    createLposItems("15", "4")
};

Depending on where the values are coming from, you could build this array using a loop, too.

Robert
  • 8,406
  • 9
  • 38
  • 57
1

You can use a for loop to simplify this. You can also have those two string arrays loaded from a file.

String entriesA[] = {"24341", "62", "40", "62", "14", "15"};

String entriesB[] = {"14", "49", "4", "63", "4", "4"};

List<LposItems> items = new ArrayList<LposItems>();

for (int i=0; i<entriesA.size(); i++)
{
    items.add(new LposItems());
    items.get(i).setA(entriesA[i]);
    items.get(i).setB(entriesB[i]);
}

another approach with a factory class

public class LposItemsFactory
{
    public static LposItems getLposItems(String A, String B)
    {
        LposItems item = new LposItems();
        item.setA(A);
        item.setB(B);
        return item;
    }
}

then you can use this method to generate the items in the same loop

another approach with a wrapper class

public class LposItemsWrapper extends LposItems
{
    public LposItemsWrapper(String A, String B)
    {
        setA(A);
        setB(B);
    }
}

and then you can use that class instead of LposItems

Kariem
  • 750
  • 5
  • 13