KISHORE_ZE
KISHORE_ZE

Reputation: 1476

Converting ArrayLists to Arrays (A bit different)

I know this question is asked a lot of times in Stack Overflow but mine is a bit different.

I understand that ArrayList begin at index 1 and Arrays begin at index 0. Am I right?

If not then when I convert my ArrayList to an Array.

Ex: code

List<String> list = new ArrayList<String>();

list.add("India");
list.add("Switzerland");
list.add("Italy");
list.add("France");

String [] countries = list.toArray(new String[list.size()]);

So if I my first comment was right (If it was. Because on the net I find 3/4 people saying array list begins at 0 at 1/4 saying array list begins at 1. I am a beginner so I have no idea, which is correct?

So if ArrayList begin at 1.

So can the Ex: Code be converted to

List<String> list = new ArrayList<String>();

list.add("India");
list.add("Switzerland");
list.add("Italy");
list.add("France");

String [] countries = list.toArray(new String[list.size()-1]);

Pls. do let me know. Thanks!

Upvotes: 2

Views: 135

Answers (3)

itwasntme
itwasntme

Reputation: 1462

String [] countries = list.toArray(new String[list.size()-1])

This line of code will produce an array with countries from given list decreased by one last row.

Both arrays and lists indexing starts with 0 in Java. Every first element in arrays and lists begin with index equal to 0. Every list from JAVA API implements Collection interface and its size() method returns exact number of elements in used collection.

Check out this: Java ArrayList Index

Upvotes: 4

jelmood jasser
jelmood jasser

Reputation: 918

ArrayList is like normal Arrays starts at index 0.

You can check using this code.

ArrayList<String> list= new ArrayList<String>();

list.add("one");
list.add("two");
list.add("three");

for (int i = 0; i < list.size(); i++) {
    System.out.println(i);
            System.out.println(list.get(i)); } 

Upvotes: 2

Nick Bailey
Nick Bailey

Reputation: 3162

ArrayLists are zero based for indexing, as are all collections in Java, JavaScript, Python, Ruby, C#, R, C...

Upvotes: 1

Related Questions