hello I have a commaseparated list of string and put into an array.
I ultimately need them as a list of shorts, but the only way I know how to do that is get them as an array of shorts then do array.asList()
String[] stringArray= commaSeparatedString.split("\\s*,\\s*");
How can I get that to an array of shorts so I can throw in a list?
THanks
Well presumably you just need to parse each element. But why not just add them to an ArrayList<Short>?
List<Short> shortList = new ArrayList<Short>(stringArray.length);
for (int i = 0; i < stringArray.length; i++) {
shortList.add(Short.valueOf(stringArray[i]));
}
(Note that you can't have a list of a primitive type, as Java generics don't support primitive type arguments.)
After the splitting you parse each string to the desired type for example Short.parseShort(element)
Related
I am a List of Long type and would like to convert it to an array of long type.
However when adding elements to the list, it says it is unable to find method "add(int)"
my code looks like below
package collections;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class ListToArray {
private static List<Long> list;
public static void main(String[] args){
list=new ArrayList<Long>();
list.add(121145788);
list.add(1245898);
long[] arr=new long[list.size()];
arr=list.toArray();
}
}
Error I am getting are
Error(16,13): cannot find method add(int).
Error(21,25): incompatible types
Can someone point out where it's going wrong.
As suggested in the comments, you should add L to force the value to be a long:
list.add(121145788L);
list.add(1245898L);
Explanation:
the values you wanted to add are ints, and list is for longs. Adding the L makes the compiler use the number literal as a value of type Long explicitly, and that can be added to the list.
Without it, the numbers are treated as Integers, and those can't be added to a list of type Long, hence
cannot find method add(int)
There is a method add(long), and that's what is used when the L is used.
To convert to an array, you need to do it the old fashioned way:
for (int i = 0; i < arr.length; i++) {
arr[i]=list.get(i);
}
This is because long is a primitive, and Long is a reference type (i.e. it is an Object). Casting from primitives to Objects isn't always easy. In this case, the old fashioned way works well.
First, this is your code but with all the fixes!
private static List<Long> list;
public static void main(String[] args){
list=new ArrayList<Long>();
list.add(121145788L);
list.add(1245898L);
Long[] arr = new Long[list.size()];
list.toArray(arr);
}
And here is some explanation:
you have a list of type Long. When you add() items to the list - compiler expects them to be of type Long, but you are adding literal values (plain numbers like 121145788) so those are treated as integers (type int) and are autoboxed to Integer instead of Long. So add L to treat literals as long and then they are autoboxed into Long. Fine for the compiler :)
list.toArray(arr); this is the correct method to kinda convert a list to an array. Because the method you used returns array of Object and arr you created is not an array of Object.
And again this correct method I used takes T[] as input, so you need to change your arr declaration a bit to make it of type Long instead of an array of primitive type long.
If for some reason you need long[], the easiest way would be:
long[] arr = new long[list.size()];
for (int i=0; i < list.size(); i++) {
arr[i] = list.get(i);
}
Error(16,13): cannot find method add(int), this is because you are passing int instead of a Long value in a list of Long. You should be doing:
list.add(121145788l);
And for the second error follow this.Hope,it helps!
JVM doesn't automatically cast int (short, byte, char) to Long. It's explained on the next link.
Java: Why can't I cast int to Long
Converting List<Long> to long[] is possible and also is answered on SO.
How to convert List<Integer> to int[] in Java?
That's the answers:
using Java 8 streams
long[] arr = list.stream().mapToLong(Long::longValue).toArray();
using Guava
long[] arr = Longs.toArray(list);
using Apache Commons Lang
long[] arr = ArrayUtils.toPrimitive(list.toArray(new Long[0]))
If I want to create an "unlimited" array I know I can use a list (There is a lot of information on this and other forums)
But what if I don't want to make a list? Is there another way?
Because I want to use a float array in another function and it's kind of a hassle to use a list in this case.
This is what I wrote so far with the listing
List<Float> listfloat = new ArrayList();
listfloat.add((float)0.1); //example
listfloat.add((float)1.2);
float data[]= new float[listfloat.size()];
for(int i = 0; i < listfloat.size(); ++i)
{
data[i] = listfloat.get(i);
}
return data ;
But I would prefer something like this
float data[]; //unknown size
for(i=0 ; i< sizeiwant; i++)
{
data[i] = mydata;
}
return data ;
I know that it will work! I just want to optimise my coding =)
Thank you for reading =)
There are 2 ways you can do this:
You could convert a list to an Array using list.ToArray()
You could dynamically resize the array by changing the size of the array every time you add an element to the array. Here is how you would do that:
//initialize array of size 10.
int[] array=new int[10];
//make copy of array
int[] arrayCopy=array.clone();
//expand array size by 1
array=new int[array.length+1];
//give value to new array index
array[array.length-1]=0;
//copy values from 'arrayCopy' to array
for(int x=0;x<arrayCopy.length;x++){
array[x]=arrayCopy[x];
}
Hope this helped.
With the information you provided I would recommend to use an Array and create a method that is called when your array is full and returns a copy of the original array with more space in this way is you are kind of simulating dynamic size allocation.
Arrays in java are fixed-size, so your second piece of code is never going to work.
If you want a data type that can resize, you should use an ArrayList. On the other hand, there are times when using primitive array like a float[] is quicker and more convenient.
As a result, the need to convert between List<Float> and float[] in the way you do it in the first block of code is fairly common, and there is no way to do it in one line (unless you use an external library).
I advise writing a utility method to do the conversion
public static float[] listToArray(List<Float> list) {
int size = list.size();
float[] temp = new float[size];
for (int i = 0; i < size; i++)
temp[i] = list.get(i);
return temp;
}
(This method could be improved, as it has poor performance for a LinkedList where get is linear).
Annoyingly, you need 8 methods like this for the 8 primitive types, and 8 methods to do the conversions in the other direction. As things stand at the moment, there is no way to write generic code over primitive types, so code duplication like this is common.
In a mapreduce code, while converting list to array of (org.apache.hadoop.io.Text) Text type, receiving ArrayStoreException.
List<String> testList= new ArrayList<String>();
testList.add("testData1");
testList.add("testData2");
Text[] testArray=testList.toArray(new Text[testList.size()]);
but when i dont add any value to the list and then convert it to array, it works fine(with null values). Can some one please point my mistake.
You can't store Strings in a Text array (Text[]).
You can store them in a String array (String[]) :
String[] testArray=testList.toArray(new String[testList.size()]);
when i dont add any value to the list and then convert it to array, it works fine
It only works since you are creating an empty array in this case, so nothing is stored in it.
If you must produce a Text[] that contains the data from the source List<String>, you have to iterate over the List and produce the Text instances yourself:
Text[] testArray = new Text[testList.size()];
for (int i = 0; i < testList.size(); i++) {
testArray[i] = new Text(testList.get(i)); // assuming the Text class
// has such a constructor
}
I'm reading in a schema file by line as strings to determine the format of a separate binary file.
How can I convert/store the schema (represented as a string) to an array of mixed primitive data types to allow binary processing that would avoid the overhead of constant string comparisons for each element in the binary file?
Example: int int double char char int
Desired array or ArrayList: typeInt, typeInt, typeDouble, typeChar...
Gratzie
Use an Object array:
Object[] objArr = new Object[10];
objArr[0] = 1;
objArr[1] = "lol";
System.out.println(objArr[0]);
System.out.println(objArr[1]);
This should give:
1
lol
According to me, first you have to use the Wrapper Classes in java to Parse the String to the desirable type and then store these types to ArrayList because arraylist has good memory management as well as many ready mate methods, so it is very easy to work with it
You can take some hint from this peace of code
int foo = Integer.parseInt("1234");
String xyz = "hello";
List list1 = new ArrayList<>();
list1.add(foo);
list1.add(xyz );
You can also create a ArrayList of Objects.
import java.util.ArrayList;
ArrayList<Object> listObj = new ArrayList<Object>();
listObj.add(1);
listObj.add("Some string");
listObj.add(new ArrayList<Object>());
I am trying to write a method that takes in an Object[] that is populated with tokens and converts it to an array of integers.
I started out with an ArrayList:
ArrayList<String> colArr = new ArrayList<String>();
then populated it with tokens from a .txt file:
while(st.hasMoreTokens()){
colArr.add(st.nextToken());
}
then converted it to an Object[]:
Object[] newColArr = colArr.toArray();
I now need to write a method that converts this Object[] to an Integer so that I can add certain elements together. This is what I tried:
public static Integer[] convert(Object[] objectArray){
Integer[] intArray = new Integer[objectArray.length];
for(int i=0; i<objectArray.length; i++){
intArray[i] = (Integer) objectArray[i];
}
return intArray;
}
but got "Error: java.lang.String cannot be cast to java.lang.Integer".
use Integer.valueOf(objectArray[i]) instead of casting like (Integer)objectArray[i]
EDIT:
To clarify, remember that Integer.valueOf() is simply a boxed object around Integer.parseInt().. so you have to handle NumberFormatException.
If you are quite sure that your text file will only contain integers, you could simply have an arraylist of integers and do the Integer.valueOf(tokenizer.nextToken())
Integer.parseInt( string ); works for getting an Integer from String
loop through your array of strings and use Integer.parseInt();
You can't typecast directly from a java.lang.String to a java.lang.Integer, they are two totally different objects. Instead try doing:
Integer.parseInt(objectArray[i])
Don't forget to handle java.lang.NumberFormatException. And one more thing, you don't need to do the intermediary conversion to Object array. Unless of course your using that for something else you didn't mention. Cheers.
if you know, that the object array contains strings, you can use Integer.parseInt() to convert the String to a Integer
You can also use guava's Lists.transform.
List<String> numberList=Lists.newArrayList("1","2","3");
List<Integer> trnsList = Lists.transform(numberList,new Function<String,Integer>() {
#Override
public Integer apply(String arg0) {
return Integer.valueOf(arg0);
}
});
Integer[] intArr=trnsList.toArray(new Integer[trnsList.size()]);