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!
-
The change I made in the second code is that: 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]); marked in boldKISHORE_ZE– KISHORE_ZE2015年08月15日 14:47:14 +00:00Commented Aug 15, 2015 at 14:47
-
This question has no connection to androidzkminusck– zkminusck2015年08月15日 14:51:18 +00:00Commented Aug 15, 2015 at 14:51
-
Ok its related to an app I'm making but if you say so. I'll remove that tagKISHORE_ZE– KISHORE_ZE2015年08月15日 14:52:39 +00:00Commented Aug 15, 2015 at 14:52
3 Answers 3
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
10 Comments
.size() property. The number of Strings added were 7. So if you are right shouldn't the size be 6. Yet it showed me `.size()' = 7.index of List is for tracking current element that you work on. And size is exact amount of elements inside it.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)); }
Comments
ArrayLists are zero based for indexing, as are all collections in Java, JavaScript, Python, Ruby, C#, R, C...
3 Comments
Explore related questions
See similar questions with these tags.