ArrayList to Array of Strings in java - java

ArrayList<String> newArray = new ArrayList<String>();
newArray = urlList.getUrl();
for( int i = 0 ; i < newArray.size();i++)
{
System.out.println(newArray.get(i));
}
newArray.toArray(mStrings );// is this correct
mStrings = newArray.toArray();// or this to convert ArrayList ot String array here
for( int i = 0 ; i < mStrings.length;i++)
{
System.out.println(mStrings[i]);
}
EDIT: when i try as below, I get null pointer exception:
try
{
newArray.toArray(mStrings );
for(int i = 0 ; i < mStrings.length; i++)
{
System.out.println(mStrings[i]);
}
} catch( NullPointerException e )
{
System.out.println(e);
}

Usually I write
String[] array = collection.toArray(new String[collection.size()]);
because this way
I get an array of the type that I want.
I don't have to declare the array before calling Collection.toArray(T[]).

Depends on what you want to do. Both are correct
toArray()
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
Refer here
toArray(T[] a)
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.
Refer here
In former, you want to get an array. In latter you have an array, you just wanted to fill it up.
In your case, first form is preferred as you just want to get an array without bothering size or details.
Basically this is what happens in 2nd case:
List's size is measures.
(a) If list size is less than that of the array provided, new Array of the type provided as argument is created.(b)Else, the list is dumped in the specified array.
The only benefit of doing so, is you avoid casting. The two form are the same. If you use Object array. i.e.
myList.toArray() <==> toArray(new Object[0])
Now, If you pass an uninitialized array, you will get a NullPointerException. The best way to do it is:
String[] y = x.toArray(new String[0]);
Please read the document

The first option is better as it allows you to pass in a typed array, which is then populated inside the method.
The second option returns an Object[] - so you would have to cast it to use String methods.

In plain java i'm use something like
rolesList.toArray(new Integer[rolesList.size()]);
for converting list to array. Don't know in android.

How about this
List a = new ArrayList();
a.add("wer");
a.add("sff");
String[] f= (String[]) a.toArray(new String[0]);
System.out.println(f[0]);

Related

Incomparable object types --> Object to string? [duplicate]

This question already has answers here:
make arrayList.toArray() return more specific types
(6 answers)
Closed 4 years ago.
The method I have is supposed to return a String [] so i used toArray method. But I get error regarding object cannot be converted to strings. I have initialized the list as String as well and am unable to figure out the error that I am getting. Everywhere I read, they say initialize as String and I have already done that. how can I fix it??
ArrayList<String> c = new ArrayList<String>(Arrays.asList(a));
.......(job done)
return c.toArray();
--The entire code:
public static String[] anagrams(String [] a) {
ArrayList<String> b = new ArrayList<String>(Arrays.asList(a));
ArrayList<String> c = new ArrayList<String>(Arrays.asList(a));
int l=a.length;
int i,j;
for (i=0;i<l;i++) {
for (j=i+1;j<l;j++) {
if (check(b.get(i),b.get(j))){
if (c.contains(b.get(j)))
c.remove(j);
}
}
}
return c.toArray();
}
Tryy this
return c.toArray(new String[c.size()]);
This basically initializes size of the array
There are two toArray methods in an ArrayList. From the docs:
Object[] toArray()
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
<T> T[] toArray(T[] a)
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
Right now you are using the first version, which returns an Object array. Since you want a String array, not an Object array, you must use the second version:
return c.toArray(new String[0]);
The array parameter is needed so ArrayList knows which type to return. If you provide an empty array, ArrayList will allocate a new array for the desired type. However you can also provide an array that is big enough for all elements of the list, then ArrayList will use that array instead of initializing a new one:
return c.toArray(new String[c.size()]);

for-each loop in java can't be used for assignments

Why for-each loop in java can't be used for assignments?
For eg I am trying the below example and not getting the expected result but compiles successfully:
int count = 0;
String[] obj = new String[3];
for (String ob : obj )
ob = new String("obj" + count++);
System.out.println(obj[0]); // null
ob is a local variable which is a copy of the reference in the array. You can alter it but it doesn't alter the array or collection it comes from.
Essentially, that is correct. The for-each loop is not usable for loops where you need to replace elements in a list or array as you traverse it
String[] obj = { "obj1", "obj2", "obj3" };
or
for (int count = 0; count < obj.length; count++) {
obj[count] = "obj" + count;
}
As you've noted, you can't use the variable in an array iteration to set the values of the array. In fact your code, while legal, is unusual in iterating through the elements of an array in order to initialise them. As other answers have noted, you are better off using the index of the array.
Even better is to create the array in the process of initialisation. For example, in Java 8 you could use:
String[] obj = IntStream.range(0, 4).mapToObj(n -> "obj" + n).toArray();
This seems to me to capture your intent of creating strings and then turning them into a new array rather than create an array and then iterate through it changing each element.

Pass An Array as Argument Having a Different Start Index

How can I pass arrays in Java where I can indicate a different start index (0th index) for the array argument. In C++, you can pass arrays like this
myMethed(myArray + 3); // passing method where begin index is 4th element
...
void myMethod(int* arr) {
int val = arr[0]; // refers to the 4th element
int val2 = arr[1]; // 5th element
}
How can I do something similar in Java. I tried copying a subset of the array using Arrays.copyOfRange but I don't want a separate copy but the same array with a different start index.
Of course I can do this:
myMethod(int[] arr, int startIndex) {
int val = arr[startIndex];
int val2 = arr[startIndex + 1];
}
But are there other ways without declaring a separate parameter for start index?
Thanks a lot.
but the same array with a different start index.
In Java, an array is an object whose size is defined at the point it is initialized. The starting index is always zero and the size is fixed. These two cannot be altered after memory has been allocated. In Java same array means same object and not a memory space.
Java doesn't allow you to slice the allocated memory as a new array. So, you will always need to create another array, or explicitly pass the starting index to the method you are calling.
In general, prefer collections over arrays. Your particular need can be solved by using Lists instead:
myMethod(List<Integer> list) {
int val = list.get(0);
int val2 = list.get(1);
}
...
List<Integer> myList = ...;
myMethod(myList.subList(3, myList.size()));
From the List.subList documentation:
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.
(emphasis mine)
You can create an iterator, move it to the required position and pass it as a method argument.
what about this ?
Integer myarr[] = new Integer[] { 1, 2, 3, 4 };
System.out.println(Arrays.toString(Arrays.asList(myarr).subList(2, myarr.length).toArray(new Integer[2])));

ArrayList compiler error

I am trying to make an array list in Java in two spots, but I don't know what I am doing wrong. It says an array is required, but I don't know what that means because I am using an array list.
This is the line that's being messed up:
static char rSpaces(String problem, int count)
{
num.add(problem.charAt(count));
char no = num[count];
return no;
}
If this helps, this is the line I created the array list in (I already imported it):
static ArrayList<Character> num = new ArrayList<Character>();
num[count] is wrong, since num is not an array. Use num.get(count) instead.
An ArrayList is not an array, so you can't use the array element [] syntax here.
With an ArrayList, use the get method to access an element.
You should use ArrayList.get to access the elements of an ArrayList. Change that to:
char no = num.get(count);
Java array and ArrayList are different things.
You could access the size of the ArrayList by using method size as follows:
static char rSpaces(String problem, int count)
{
num.add(problem.charAt(count));
char no = num.get(count);
return no;
}
If you want to access it as an array, you could "export" it using the toArray method as follows:
...
Character[] myArray = num.toArray(new Character[]{})
Character c = myArray[count];
...
To access element of array use index operation using [] operator num[count] while in case of ArrayList you need to use get(count) method.

For-Each and Pointers in Java [duplicate]

This question already has answers here:
Why does the foreach statement not change the element value?
(6 answers)
Closed 5 years ago.
Ok, so I'm tyring to iterate through an ArrayList and remove a specefic element. However, I am having some trouble using the For-Each like structure. When I run the following code:
ArrayList<String> arr = new ArrayList<String>();
//... fill with some values (doesn't really matter)
for(String t : arr)
{
t = " some other value "; //hoping this would change the actual array
}
for(String t : arr)
{
System.out.println(t); //however, I still get the same array here
}
My question in, how can I make 't' a pointer to 'arr' so that I am able to change the values in a for-each loop? I know I could loop through the ArrayList using a different structure, but this one looks so clean and readable, it would just be nice to be able to make 't' a pointer.
All comments are appreciated! Even if you say I should just suck it up and use a different construct.
I think the best approach may be to use a for loop.
ArrayList<String> arr = new ArrayList<String>();
for (int i = 0; i < arr.size(); i++) {
String t = arr.get(i);
if (// your condition is met) {
arr.set(i, "your new value");
}
}
The problem is that you're trying to change the loop-scoped reference t to let it point to a new String instance. This ain't going to work. It does not refer the actual entry in the arraylist. You need to change the actual value of the reference. If String was mutable and provided a fictive set() method for that, you could in theory do
for (String t : arr) {
t.set("some other value");
}
or so, but that's not possible as it is immutable. Better get a handle of the entrypoint in the array itself using the normal for loop:
for (int i = 0; i < arr.size(); i++) {
arr.set(i, "some other value");
}
If you insist in using the enhanced for loop, then you need to replace String by StringBuilder, which is mutable:
for (StringBuilder t : arr) {
t.delete(0, t.length()).append("some other value");
}
Remember, Java is pass-by-value, not pass-by-reference.
For-each doesn't give you an index pointer, so you just can't use it to change an immutable value.
Either use a for-loop with an index or use a mutable type (like StringBuffer, not String)
An array of objects (like strings) in Java is a contiguous block containing an ordered series of references. So, when you have an array of 4 strings, what you really have is 4 references stored IN the array, and 4 string objects that are outside of the array but are referenced by its 4 elements.
What the for-each construct in Java does is create a local variable and, for each iteration, copy into that local variable the reference from the array cell that corresponds to that iteration. When you set the loop variable (t = " some other value") you are putting a reference to a new string, "some other value", into the local variable t, not into the array.
The contrasts with some other languages (like Perl) where the loop variable acts like an alias to the array/list element itself.
Your code is re-written by the compiler as something like this:
ArrayList<String> arr = new ArrayList<String>();
//... fill with some values (doesn't really matter)
for (final Iterator <String> i = arr.iterator(); i.hasNext();) {
String t;
t = i.next();
t = " some other value "; // just changes where t is pointing
}
To do what you want you would have to write the for loop like this:
for (final ListIterator<String> i = arr.iterator(); i.hasNext();) {
final String t;
t = i.next();
i.set("some other value");
}
Iterator does not have the set method, only ListIterator does.
Basically you want to remove the String t from the list arr. Just do a arr.remove(t) and you could be done. But you can't do it while iterating over the same list. You'll get an Exception if you try to modify the list this way.
You have two options:
clone your list, iterate through the clone and remove the 'specific' String from the original list
create a list for delete candidates, add all 'specific' Strings to that list and, after iterating through the original list, iterate through the wastebin and remove everything you've collected here from the original list.
Option 1 is the easist, the clone can be made like:
List<String> clone = new ArrayList<String>(arr);
You seem to misunderstand how objects/references work in Java, which is pretty fundamental to using the language effectively. However, this code here should do what you want (apologies for the lack of explanation):
ArrayList<String> arr = new ArrayList<String>();
//... fill with some values (doesn't really matter)
for(int i = 0; i < arr.size(); i++)
{
arr.set(i, " some other value "); // change the contents of the array
}
for(String t : arr)
{
System.out.println(t);
}
I believe, this is not related to immutable or mutable.
t = " some other value "; //hoping this would change the actual array
t does not hold the reference to actual object. Java copies the value from arraylist and puts that value into t so array list value does not get affect.
HTH
This has been answered well. Still here is my suggestion. The var t inside loop is only visible there. It will not be seen outside the loop. You could do t.set() if it was not String.
Use a StringBuffer rather than plain strings. This way the string within is mutable.
Strings are immutable. If you had a mutable type like StringBuilder/Buffer, you could change the string in your iteration. You do have references, remember.

Categories

Resources