1

Is there any way I can input data into any array list without actually doing the following in each place in the code where I need to insert data?

ArrayList<dataType> kwh = new ArrayList<dataType>();
arrayListVariable.add(data);
arrayListVariable.add(moreData);
arrayListVariable.add(evenMoreData);

As of right now, this seems to be very time consuming if I need to put in quite a bit of data into the array list. Is there a simpler/more concise way of doing this?

0

2 Answers 2

5

You could use like:

ArrayList<dataType> kwh = new ArrayList<dataType>(Arrays.asList(data, moreData, evenMoreData));

Alternatively, you could use Guava's Lists class.

To add new elements:

List<Integer> ints = Lists.newArrayList(1, 2, 3);

However, this one is not fixed size. You can add new elements just by calling ints.add() afterwards.

Sign up to request clarification or add additional context in comments.

8 Comments

This creates a fixed sized List, so it doesn't fit a scenario in which you have to add elements all the time.
You can also have list.addAll(asList(data, moreData, evenMoreData)).
Required: java.util.ArrayList <Integer>
Just do new ArrayList<Integer>(Arrays.asList(data, more));
@VishvakSeenichamy I've edited this answer (it didn't compile before). This is the version you should use if you need to add/remove elements after this. If the List is read-only after creation, all you need is List<Integer> list = Arrays.asList(...); as Marco Topolnik says,
|
0

That depends upon what you mean by "faster".

If you're talking about how fast the program runs, the add() method runs in constant time. You're not going to get much better than that unless you use an actual array. You're using an ArrayList, though, so I'm going to assume you're willing to trade away some of the speed/space optimization for the flexibility.

If you mean "How can I add a lot of data to a list without a lot of typing", then answer is this: It depends upon what you're doing.

If you're reading from a file, create a method that splits files by whatever separator is used between data elements. Loop through these items and add them to your ArrayList.

If you're doing something else, then you're going to have to find a way to loop through the data . Once you get it into an array, the rest is pretty simple.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.