Syler
Syler

Reputation: 477

Java Array List Creation

Painfully newbie question I know, but I'm very new to Java Programming.

I have 4 values, value1, value2, value3 and value4. I'd like a method that will return all 4 values, but I think I need an ArrayList to do so. All these values are in the same class, and the method will be within this class too.

I've never created one before, and Google doesn't really offer an answer I can understand at my very early level of Java understanding. Any help on how I create one for this?

(I assume I need an ArrayList, but I may be wrong)

Upvotes: 1

Views: 159

Answers (4)

Angelo Fuchs
Angelo Fuchs

Reputation: 9941

public List method() {
    ArrayList list = new ArrayList();
    list.add(item1);
    list.add(item2);
    list.add(item3);
    list.add(item4);
    return list;
}

But it most likely is better to have an inner wrapper class for that. Because that way you can give the various Objects meaningful names.

public DataClass method() {
    DataClass retVal = new DataClass(item1, item2, item3, item4);
}

private class DataClass {
    Object item1;
    Object item2;
    Object item3;
    Object item4;
    public DataClass(Object item1, Object item2, Object item3, Object item4) {
        this.item1 = item1;
        this.item2 = item2;
        this.item3 = item3;
        this.item4 = item4;
    }
}

Upvotes: 1

Ioan
Ioan

Reputation: 5187

If you want to use java.util.List functionality you can simply use :

List<String> predefinedList = Arrays.asList(new String[] { "value1", "value2", "value3", "value4" });

and then in a method simply do return predefinedList;

Otherwise, if you only want to return an array of predefined values, then you can just use the following notation in your method: return String[] { "value1", "value2", "value3", "value4" }

Upvotes: 0

Darshan Mehta
Darshan Mehta

Reputation: 30809

You can also declare and fill the array list at the same time:

List<String> list = new ArrayList<String>(){{
     add("A");
     add("B");
     add("C");
}};

Upvotes: 2

tckmn
tckmn

Reputation: 59273

You can just use a normal array. For example:

int[] getValues() {
    int value1 = 10, value2 = 20, value3 = -5, value4 = 3;
    int[] arr = new int[] {value1, value2, value3, value4};
    return arr;
}

No need to use an ArrayList when you know how many items you will always need.

It would be better to have an array, since they are native and therefore faster, less bloated, and much more simple.

Upvotes: 2

Related Questions