0

How to populate the array without iterating it with known size and value?

Example: If I want to create an array of size 5 with values 1. I don't want to iterate with size 5 and use add method. Is there any other way?

3
  • 'Array of size 5 with values 1' can u explain a bit more? Commented Nov 1, 2011 at 7:20
  • 2
    I am not sure what data structure you are talking about when you say "use add method". Are you referring to a list rather than an array? Commented Nov 1, 2011 at 7:21
  • @suraj:its always better to specify your requirements and use case to get better inputs from community Commented Nov 1, 2011 at 7:28

4 Answers 4

2

Instantiating a string array with variables:

String foo = getFoo();
String bar = getBar();
String[] myStringArray = { foo, bar};

Instantiating a string with literals:

String[] myStringArray = {"foo", "bar"};

Filling an existing array with some value:

Arrays.fill(myStringArray, "1");
Sign up to request clarification or add additional context in comments.

Comments

1
int[] array = new int[5];
Arrays.fill(array, 1);

This should work.

1 Comment

I do not know what he was asking, as arrays do not have an add method :D
1

i believe you can achieve that by following

int[] array = new int[5];
Arrays.fill(array, 0);

additionally you can check following link

Array Fill

Comments

0
int[] arr = new int[5];
Arrays.fill(arr,1);

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.