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.
Related
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()]);
resultList = [[[Computer lessons], [Leon, Maria]], [[Computer repair], [Jack, Leon]], [[Data recovery service], [Leon]], [[Handyman], [Jack]], [[House cleaning], [Jack, Maria]]]
String[][][] result = new String [resultList.size()][][];
int count = 0;
for(ArrayList<ArrayList<String>> nestedList:resultList) {
result[count]= nestedList.stream().map(List::toArray).toArray(String[][]::new);
count ++;
}
The code above initializes an ArrayList<ArrayList<ArrayList<String>>> with some values. then tries to put its content in a 3-dimensional String Array.(String [][][]). The code generates the following exception:
java.lang.ArrayStoreException: [Ljava.lang.Object;
Please advise.
Let's break it up:
nestedList.stream().map(List::toArray)
As per its definition, nestedList is an ArrayList<ArrayList<String>>.
Therefore, nestedList.stream() is a Stream of ArrayList<String>.
And .map(List::toArray) applies the toArray() method on each ArrayList<String> to turn it into a stream of Object[] arrays. There's your problem. You are using the toArray() method without arguments, which returns an Object array instead of a String array. You need instead to use the toArray(String[]) method.
.map(list -> list.toArray(new String[list.size()]))
I have a String variable named List.I want to get the first char of the String which is in the List.
The problem is, that I cannot use the charAt() function on the List.
Here is my effort so far:
List<String> testList = new ArrayList<>();
testList.get(3).chatAt(0);
The code you have given should work (apart from the typo). It retrieves the 4th item in the list, which we know is a String because have defined the list as a list of Strings, and then gets the first character of that String. It will obviously break if there are not 4 things in the list, or if the String doesn't have any characters in it.
List<String> testList = new ArrayList<>();
testList.get(3).charAt(0);
You can make things a bit clearer by declaring the String as a variable before you call charAt on it.
String s = testList.get(3);
char c = s.charAt(0);
Methods get(String s)
is not available for arrays in Java, probably you confused it with methods of Java Collection Framework (list).
If you have an array of string you must first access on the element with array[i]
and after call the method charAt(int index).
Finally you must use array[i].charAt(index)
where i is the position in the array to the string that you search and index the index of character you must search in the string.
I am trying to create a method to takes an array of names and returns a copy of the list with the names randomly rearranged. The code below returns a new list with duplicated names. what can I do to shuffle names of the new list instead?
public static String[] shuffle(String []names)
{
int num =0;
String [] newArray = new String [names.length];
Random r = new Random ();
for(int i = 0; i<names.length; i++){
num = r.nextInt(names.length);
if((i-1)!=num){
newArray[i]=names[num];
}
}
return newArray;
}
You can use Collections.shuffle() to shuffle a list.
If you are eager to do it by your own - have a look on fisher-yates shuffle.
(Pseudo code:)
for (i = n-1; i >= 0; i--)
swap(names,i,r.nextInt(i+1));
(Where swap() is a standard swapping function to swap two elements in an array)
(Note, if you want a new instance with the shuffled array - just copy it using Arrays.copyOf() before running the algorithm.
Like others have suggested there are already other cleaver/easy ways to do this, but to solve the issue in your code you need to make the newArray a copy of the names array (you can can use Arrays.copyOf) and then properly swap the values, like:
if(i!=num){
String aux=newArray[i];
newArray[i]=newArray[num];
newArray[num]=aux;
}
Collections.shuffle(list)
Info
You can use the ToList to make it a list for the shuffle and then back to an array with ToArray.
This may not be the most efficient but it is the easiest.
public String[] shuffle(String[] ss) {
List<String> list = Collections.shuffle(Arrays.asList(ss));
return list.toArray(new String[ss.length]);
}
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]);