4
4
4ainik2016-11-24 18:41:37
Java
4ainik, 2016-11-24 18:41:37

How to work with arrays in Java?

How to work with arrays in java or rather in android?
The task is this: you need to accumulate some data that comes in batches of unknown length, with the possibility of their subsequent processing. I don't want to mess with files.
input data array short[].
I tried ArrayList, but when I try to access the element ( a.get(index) ) as an integer, I get a compile-time error "The operator * is undefined for the argument type(s) int, Object"
i.e. it turns out that ArrayList does not store an array, but an object, and how to convert it back to an array is not clear, more precisely, it is not clear how to work with individual elements

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey Myvrenik, 2016-11-24
@gim0

I suspect you are trying to do something like List<short> arr;. The fact is that collections (which include ArrayList) can only store objects, i.e. cannot store primitives as is. To store short values ​​in an ArrayList, use the Short wrapper :List<Short> arr;

4
4ainik, 2016-11-24
@4ainik

ArrayList a = new ArrayList();
for(int j = 0; j < x; j++){
short[] buf = new short[200];
count = func(buf, 200);
for(int i = 0; i < count; i++){
  a.add(buf[i]);
}
}

...
after the accumulation of data I try to process
int sum = 0;
for(int i = 0; i < a.size(); i++){
   sum += a.get(i); //тут собственно не важно какая операция сложение/умножение, 
ошибка та же, что объект не может быть преобразован к int
}

I also tried using the C type, vector :)
but there is again some kind of trouble when declaring
"Syntax error, insert "Dimensions" to complete ReferenceType"

F
Frozen Coder, 2016-11-25
@frozen_coder

List<Short> a = new ArrayList();
For good, choose one thing - either arrays or collections. Better than collections, I don’t remember arrays at all when I last used them.
As already advised above, read about Collections, Generics, Autoboxing.

for(int i = 0; i < a.size(); i++){
sum += a.get(i);
}

And instead of for with collections, you can use for each. And by the way, why use short first, and then switch to int? Can it be better at once in int?
Integer sum = 0;
for(Short item : a){
     sum += (Integer) item;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question